Esempio n. 1
0
        internal RSACryptoSystem( BackgroundWorker UseWorker, RSACryptoWorkerInfo UseWInfo )
        {
            Worker = UseWorker;
            WorkerInfo = UseWInfo;
            StartTime = new ECTime();
            StartTime.SetToNow();

            RngCsp = new RNGCryptoServiceProvider();
            IntMath = new IntegerMath();
            IntMathNewForP = new IntegerMathNew( IntMath );
            IntMathNewForQ = new IntegerMathNew( IntMath );

            Worker.ReportProgress( 0, IntMath.GetStatusString() );
            Quotient = new Integer();
            Remainder = new Integer();
            PrimeP = new Integer();
            PrimeQ = new Integer();
            PrimePMinus1 = new Integer();
            PrimeQMinus1 = new Integer();
            PubKeyN = new Integer();
            PubKeyExponent = new Integer();
            PrivKInverseExponent = new Integer();
            PrivKInverseExponentDP = new Integer();
            PrivKInverseExponentDQ = new Integer();
            QInv = new Integer();
            PhiN = new Integer();
            TestForDecrypt = new Integer();
            M1ForInverse = new Integer();
            M2ForInverse = new Integer();
            HForQInv = new Integer();
            M1MinusM2 = new Integer();
            M1M2SizeDiff = new Integer();

            PubKeyExponent.SetFromULong( PubKeyExponentUint );
        }
Esempio n. 2
0
        public WebTCPClient( MainForm UseForm, TcpClient UseClient, string UseAddress )
        {
            MForm = UseForm;
            RemoteAddress = UseAddress;

            LastTransactTime = new ECTime();
            LastTransactTime.SetToNow();
            LinesDictionary = new Dictionary<string, string>();

            if( UseClient == null )
              Client = new TcpClient();
            else
              Client = UseClient;

            try
            {
            NetStream = Client.GetStream();
            }
            catch( Exception Except )
              {
              MForm.ShowWebListenerFormStatus( "Exception in Creating the NetStream:" );
              MForm.ShowWebListenerFormStatus( Except.Message );
              NetStream = null;
              return;
              }

            Client.ReceiveTimeout = 3 * 1000;
            Client.SendTimeout = 3 * 1000;
            Client.SendBufferSize = 1024 * 32;
        }
Esempio n. 3
0
        internal TLSTCPClient( MainForm UseForm, TcpClient UseClient, string UseAddress )
        {
            MForm = UseForm;
            RemoteAddress = UseAddress;

            RawBuffer = new byte[RawBufferLength];
            TLSOuterRecordBuffer = new byte[MaximumTLSRecordLength + 5]; // Plus 5 for the header.

            LastTransactTime = new ECTime();
            LastTransactTime.SetToNow();

            if( UseClient == null )
              Client = new TcpClient();
            else
              Client = UseClient;

            try
            {
            NetStream = Client.GetStream();
            }
            catch( Exception Except )
              {
              MForm.ShowTLSListenerFormStatus( "Exception in Creating the NetStream:" );
              MForm.ShowTLSListenerFormStatus( Except.Message );
              NetStream = null;
              return;
              }

            Client.ReceiveTimeout = 3 * 1000;
            Client.SendTimeout = 3 * 1000;
            Client.SendBufferSize = 1024 * 32;
        }
 internal SendCustomerTLSHandshake( BackgroundWorker UseWorker, BackWorkerInfo UseWInfo )
 {
     Worker = UseWorker;
     WInfo = UseWInfo;
     StartTime = new ECTime();
     StartTime.SetToNow();
     MsgClient = new CustomerTLSClient( WInfo.ServerIPOrDomainName );
 }
Esempio n. 5
0
        internal CustomerTLSClient( string UseDomainName )
        {
            DomainName = UseDomainName;
            RawBuffer = new byte[RawBufferLength];
            TLSOuterRecordBuffer = new byte[MaximumTLSRecordLength];

            Handshake = new ProcessHandshake( DomainName );

            Client = new TcpClient();
            Client.ReceiveTimeout = 15 * 1000;
            Client.SendTimeout = 15 * 1000;
            LastReadWriteTime = new ECTime();
            LastReadWriteTime.SetToNow();
            CryptoRand = new RNGCryptoServiceProvider();
        }
Esempio n. 6
0
 internal FactorBase( QuadResWorkerInfo UseWInfo, BackgroundWorker UseWorker )
 {
     WInfo = UseWInfo;
     Worker = UseWorker;
     IntMath = new IntegerMath();
     Quotient = new Integer();
     Remainder = new Integer();
     Product = new Integer();
     ProductSqrRoot = new Integer();
     EulerExponent = new Integer();
     EulerResult = new Integer();
     EulerModulus = new Integer();
     OneMainFactor = new Integer();
     ExpOneMainFactor = new ExponentVectorNumber( IntMath );
     StartTime = new ECTime();
     StartTime.SetToNow();
     IntMath.SetFromString( Product, WInfo.PublicKeyModulus );
     IntMath.SquareRoot( Product, ProductSqrRoot );
 }
        internal QuadResCombinatorics( QuadResWorkerInfo UseWInfo, BackgroundWorker UseWorker )
        {
            WInfo = UseWInfo;
            Worker = UseWorker;
            IntMath = new IntegerMath();
            Quotient = new Integer();
            Remainder = new Integer();
            Product = new Integer();
            SolutionP = new Integer();
            SolutionQ = new Integer();
            ToDivideMod32 = new Integer();
            LastAccumulateValue = new Integer();
            GetValueBasePart = new Integer();
            StartTime = new ECTime();
            StartTime.SetToNow();

            IntMath.SetFromString( Product, WInfo.PublicKeyModulus );
            QuadResDigitsArray = new QuadResDigitsRec[DigitsArrayLength];
        }
Esempio n. 8
0
        internal TLSListenerForm( MainForm UseForm )
        {
            InitializeComponent();

            MForm = UseForm;

            DNSBackgroundWorker.WorkerReportsProgress = true;
            DNSBackgroundWorker.WorkerSupportsCancellation = true;

            ClientsLast = 0;
            // It will resize this as it needs more.
            Clients = new TLSClient[8];

            Listener = new TcpListener( IPAddress.Any, 443 );
            Listener.ExclusiveAddressUse = true;

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            UniqueEntityTag = RightNow.GetIndex(); // Start it with something new.
        }
        internal bool Connect()
        {
            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            // Worker.ReportProgress( 0, "Time: " + RightNow.ToLocalTimeString() );

            if( !MsgClient.Connect( WInfo.ServerIPOrDomainName, 443 ))
              {
              string ErrorS = "Can't connect to the server for:\r\n" +
            WInfo.ServerIPOrDomainName + "\r\n" +
            MsgClient.GetStatusString() + "\r\n";

              Worker.ReportProgress( 0, ErrorS );
              Thread.Sleep( 1000 );
              MsgClient.FreeEverything();
              return false;
              }

            Worker.ReportProgress( 0, "Connected to the server at: " + WInfo.ServerIPOrDomainName );
            return true;
        }
Esempio n. 10
0
        internal string GetRandomDomainName()
        {
            try
            {
            ECTime OldDate = new ECTime();
            OldDate.SetToNow();
            OldDate.AddMinutes( -(60 * 24 * 90)); // Go back 90 days.
            ulong OldDateIndex = OldDate.GetIndex();

            // A limited while( true ) that won't go forever.
            for( int Count = 0; Count < 10000; Count++ )
              {
              int Index = MForm.GetRandomNumber();
              Index = Index % DomainX509RecArrayLast;
              DomainX509Record Rec = DomainX509RecArray[Index];
              if( Rec.GetModifyTimeIndex() > OldDateIndex )
            continue; // Don't get a recently used one.

              // if( anything else )
            // continue;

              // return "127.0.0.1"; // For testing with local loopback.
              // return "promocodeclub.com"; // Good for testing X.509.
              return "secure.ballantinecommunications.net";
              // return "schneier.com"; //  Bruce Schneier, the cryptographer.
              // return "vantiv.com";

              // return Rec.DomainName;
              }

            return ""; // It shouldn't get here.

            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in GetRandomDomainName():" );
              MForm.ShowStatus( Except.Message );
              return "";
              }
        }
Esempio n. 11
0
        internal void AddToBadWebPageCount( string Address, string SentText )
        {
            try
            {
            IPStatusRec StatusRec;
            if( IPsDictionary.ContainsKey( Address ))
              StatusRec = IPsDictionary[Address];
            else
              StatusRec = MakeNewStatusRec();

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            StatusRec.TimeIndex = RightNow.GetIndex();
            StatusRec.BadWebPageCount++;
            StatusRec.SentText = Utility.CleanAsciiString( SentText, 2048 );

            IPsDictionary[Address] = StatusRec;
            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in AddToBadWebPageCountCount():" );
              MForm.ShowStatus( Except.Message );
              }
        }
Esempio n. 12
0
        // http://en.wikipedia.org/wiki/Internet_media_type
        internal void SendGenericWebResponse( byte[] Buffer, ulong ModifiedIndex, ulong UniqueEntity, string ContentType )
        {
            if( Client == null )
              return;

            try
            {
            // Set the initial UniqueEntity to the current date time index and then just
            // keep incrementing it.
            ECTime RightNow = new ECTime();
            RightNow.SetToNow();

            ECTime ExpireTime = new ECTime();
            ExpireTime.SetToNow();
            ExpireTime.AddSeconds( 120 );

            ECTime ModifiedTime = new ECTime( ModifiedIndex );

            // ETag is an Entity Tag.
            // "An entity tag MUST be unique across all versions of all entities
            // associated with a particular resource."
            string Header = "HTTP/1.1 200 OK\r\n" +
               "Date: " + RightNow.GetHTTPHeaderDateTime() + "\r\n" +
               "Server: Eric Example\r\n" +
               "Last-Modified: " + ModifiedTime.GetHTTPHeaderDateTime() + "\r\n" +
               "ETag: " + UniqueEntity.ToString() + "\r\n" +
               "Accept-Ranges: bytes\r\n" +
               "Content-Length: " + Buffer.Length.ToString() + "\r\n" +
               // "Cache-Control: max-age=5184000
               "Expires: " + ExpireTime.GetHTTPHeaderDateTime() + "\r\n" +
               "Keep-Alive: timeout=5, max=100\r\n" +
               "Connection: Keep-Alive\r\n" +
               "Content-Type: " + ContentType + "\r\n" +
               "\r\n"; // Empty line and then the actual bytes.

            byte[] HeaderBytes = UTF8Strings.StringToBytes( Header );
            if( HeaderBytes == null )
              return;

            byte[] AllSendBytes;

            if( GetIsHeadOnly() )
              AllSendBytes = new byte[HeaderBytes.Length];
            else
              AllSendBytes = new byte[HeaderBytes.Length + Buffer.Length];

            int Where = 0;
            for( int Count = 0; Count < HeaderBytes.Length; Count++ )
              {
              AllSendBytes[Where] = HeaderBytes[Count];
              Where++;
              }

            if( !GetIsHeadOnly() )
              {
              for( int Count = 0; Count < Buffer.Length; Count++ )
            {
            AllSendBytes[Where] = Buffer[Count];
            Where++;
            }
              }

            // This returns immediately.
            WriteBytesAsync( AllSendBytes );

            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in SendHTMLOrText():" );
              MForm.ShowStatus( Except.Message );
              }
        }
Esempio n. 13
0
        internal bool SaveToFile()
        {
            string FileName = MForm.GetDataDirectory() + "NetStats.txt";

            ECTime RecTime = new ECTime();
            // OldTime.SetToYear1999();
            // ulong OldIndex = OldTime.GetIndex();

            try
            {
            using( StreamWriter SWriter = new StreamWriter( FileName  ))
              {
              foreach( KeyValuePair<string, IPStatusRec> Kvp in IPsDictionary )
            {
            RecTime.SetFromIndex( Kvp.Value.TimeIndex );

            string Line = Kvp.Key + "\t" +
              RecTime.ToLocalTimeString() + "\t" +
              RecTime.ToLocalDateString() + "\t" +
              Kvp.Value.TimeIndex.ToString() + "\t" +
              Kvp.Value.HackerCount.ToString() + "\t" +
              Kvp.Value.TimedOutCount.ToString() + "\t" +
              Kvp.Value.GoodWebRequestCount.ToString() + "\t" +
              Kvp.Value.TotalGoodWebRequestCount.ToString() + "\t" +
              Kvp.Value.Port80Count.ToString() + "\t" +
              Kvp.Value.Port443Count.ToString() + "\t" +
              Kvp.Value.Referer + "\t" +
              Kvp.Value.UserAgent + "\t" +
              Kvp.Value.HostName + "\t" +
              Kvp.Value.LastHostNameUpdate.ToString() + "\t" +
              Kvp.Value.BadWebPageCount.ToString(); //  + "\t" +
              // Kvp.Value.SentText;

            SWriter.WriteLine( Line );
            }

              SWriter.WriteLine( " " );
              }

            return true;

            }
            catch( Exception ) //  Except )
              {
              // "Error: Could not write
              return false;
              }
        }
Esempio n. 14
0
        internal void CloseTimedOut()
        {
            ECTime OldTime = new ECTime();
            OldTime.SetToNow();
            ////////////////////////
            OldTime.AddSeconds( -4 );

            ECTime OldWebTime = new ECTime();
            OldWebTime.SetToNow();
            // Browsers that are cooperative don't open too many connections at once.
            // Denial of service people will.
            // This delay makes browsers that are cooperative hold off on sending more
            // requests until they've closed some sockets.
            // Apparently this is the operating system that is being cooperative.
            // And if this server is too busy it's not going to be calling this
            // function to close it until it can get around to it.
            // So cooperative web clients will wait.
            OldWebTime.AddSeconds( -0.1 );
            // OldWebTime.AddSeconds( 10 ); // If I put it 10 seconds in the _future_ it works.
            // OldWebTime.AddSeconds( -10 );
            // The socket is setting LastTransactTime when AsyncResult.IsCompleted.
            // So it's setting it when the socket thinks it's done sending it.
            ulong OldIndex = OldTime.GetIndex();
            ulong OldWebIndex = OldWebTime.GetIndex();
            for( int Count = 0; Count < ClientsLast; Count++ )
              {
              if( Clients[Count] == null ) // This should never happen but...
            continue;

              if( Clients[Count].IsShutDown())
            continue;

              /*
              // Close a web request only after it has started processing the request.
              if( Clients[Count].GetProcessingStarted())
            {
            if( Clients[Count].GetIsAWebRequest())
              {
              if( Clients[Count].GetLastTransactTimeIndex() < OldWebIndex )
            {
            if( Clients[Count].IsProcessingInBackground())
              {
              // ShowStatus( " " );
              // ShowStatus( "Web request is still sending." );
              // MForm.ServerLog.AddToLog( "Web Still Sending", "Nada", Clients[Count].GetRemoteAddress() );
              }

            Clients[Count].FreeEverything();
            }
              }
            }
            */

              // If it's more recent than the old index then it's OK.
              if( Clients[Count].GetLastTransactTimeIndex() > OldIndex )
            continue;

              /*
              // If this message has not already been processed.
              if( !Clients[Count].GetProcessingStarted())
            {
            string InputS = Utility.GetCleanUnicodeString( Clients[Count].GetAllInputS(), 2000 );
            InputS = InputS.Trim();
            if( InputS.Length > 0 )
              {
              // ShowStatus( "Timed out with: " + InputS );
              }

            MForm.NetStats.AddToTimedOutCount( Clients[Count].GetRemoteAddress(), InputS );
            }
            */

              if( Clients[Count].IsProcessingInBackground())
            {
            ShowStatus( " " );
            ShowStatus( "**************************************" );
            ShowStatus( "Still sending after time out period." );
            ShowStatus( "**************************************" );
            ShowStatus( " " );
            }

              // They normally time out.
              ShowStatus( "Closing timed out: " + Clients[Count].GetRemoteAddress());
              Clients[Count].FreeEverything();
              }
        }
Esempio n. 15
0
        private void ProcessOuterMessages()
        {
            if( MForm.GetIsClosing())
              return;

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            for( int Count = 0; Count < ClientsLast; Count++ )
              {
              if( Clients[Count] == null ) // This should never happen but...
            continue;

              // IsShutDown is a little slower than the above checks.
              if( Clients[Count].IsShutDown())
            continue;

              Clients[Count].ProcessOuterMessages();
              }
        }
Esempio n. 16
0
        internal void ShowUserAgents()
        {
            ECTime RecTime = new ECTime();
            MForm.ShowStatus( " " );

            MForm.ShowStatus( "User Agents:" );

            foreach( KeyValuePair<string, int> Kvp in UserAgentDictionary )
              {
              string ShowS = Kvp.Key + "\t" +
             Kvp.Value.ToString();

              MForm.ShowStatus( ShowS );
              }

            MForm.ShowStatus( " " );
        }
Esempio n. 17
0
        internal bool DecryptWithQInverse( Integer EncryptedNumber,
                                     Integer DecryptedNumber,
                                     Integer TestDecryptedNumber,
                                     Integer PubKeyN,
                                     Integer PrivKInverseExponentDP,
                                     Integer PrivKInverseExponentDQ,
                                     Integer PrimeP,
                                     Integer PrimeQ,
                                     BackgroundWorker Worker )
        {
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, "Top of DecryptWithQInverse()." );

            // QInv and the dP and dQ numbers are normally already set up before
            // you start your listening socket.
            ECTime DecryptTime = new ECTime();
            DecryptTime.SetToNow();

            // See section 5.1.2 of RFC 2437 for these steps:
            // http://tools.ietf.org/html/rfc2437
            //      2.2 Let m_1 = c^dP mod p.
            //      2.3 Let m_2 = c^dQ mod q.
            //      2.4 Let h = qInv ( m_1 - m_2 ) mod p.
            //      2.5 Let m = m_2 + hq.

            Worker.ReportProgress( 0, "EncryptedNumber: " + IntMath.ToString10( EncryptedNumber ));

            //      2.2 Let m_1 = c^dP mod p.
            TestForDecrypt.Copy( EncryptedNumber );
            IntMathNewForP.ModularPower( TestForDecrypt, PrivKInverseExponentDP, PrimeP, true );
            if( Worker.CancellationPending )
              return false;

            M1ForInverse.Copy( TestForDecrypt );

            //      2.3 Let m_2 = c^dQ mod q.
            TestForDecrypt.Copy( EncryptedNumber );
            IntMathNewForQ.ModularPower( TestForDecrypt, PrivKInverseExponentDQ, PrimeQ, true );

            if( Worker.CancellationPending )
              return false;

            M2ForInverse.Copy( TestForDecrypt );

            //      2.4 Let h = qInv ( m_1 - m_2 ) mod p.

            // How many is optimal to avoid the division?
            int HowManyIsOptimal = (PrimeP.GetIndex() * 3);
            for( int Count = 0; Count < HowManyIsOptimal; Count++ )
              {
              if( M1ForInverse.ParamIsGreater( M2ForInverse ))
            M1ForInverse.Add( PrimeP );
              else
            break;

              }

            if( M1ForInverse.ParamIsGreater( M2ForInverse ))
              {
              M1M2SizeDiff.Copy( M2ForInverse );
              IntMath.Subtract( M1M2SizeDiff, M1ForInverse );
              // Unfortunately this long Divide() has to be done.
              IntMath.Divide( M1M2SizeDiff, PrimeP, Quotient, Remainder );
              Quotient.AddULong( 1 );
              Worker.ReportProgress( 0, "The Quotient for M1M2SizeDiff is: " + IntMath.ToString10( Quotient ));
              IntMath.Multiply( Quotient, PrimeP );
              M1ForInverse.Add( Quotient );
              }

            M1MinusM2.Copy( M1ForInverse );
            IntMath.Subtract( M1MinusM2, M2ForInverse );

            if( M1MinusM2.IsNegative )
              throw( new Exception( "This is a bug. M1MinusM2.IsNegative is true." ));

            if( QInv.IsNegative )
              throw( new Exception( "This is a bug. QInv.IsNegative is true." ));

            HForQInv.Copy( M1MinusM2 );
            IntMath.Multiply( HForQInv, QInv );

            if( HForQInv.IsNegative )
              throw( new Exception( "This is a bug. HForQInv.IsNegative is true." ));

            if( PrimeP.ParamIsGreater( HForQInv ))
              {
              IntMath.Divide( HForQInv, PrimeP, Quotient, Remainder );
              HForQInv.Copy( Remainder );
              }

            //      2.5 Let m = m_2 + hq.
            DecryptedNumber.Copy( HForQInv );
            IntMath.Multiply( DecryptedNumber, PrimeQ );
            DecryptedNumber.Add( M2ForInverse );
            if( !TestDecryptedNumber.IsEqual( DecryptedNumber ))
              throw( new Exception( "!TestDecryptedNumber.IsEqual( DecryptedNumber )." ));

            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, "DecryptedNumber: " + IntMath.ToString10( DecryptedNumber ));
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, "TestDecryptedNumber: " + IntMath.ToString10( TestDecryptedNumber ));
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, "Decrypt with QInv time seconds: " + DecryptTime.GetSecondsToNow().ToString( "N2" ));
            Worker.ReportProgress( 0, " " );
            return true;
        }
Esempio n. 18
0
 private void DoGeneralConstructorThings()
 {
     ModifyTime = new ECTime();
     MostRecentIntegerValue = new Integer();
     BitStreamRecArray = new BitStreamRec[8];
 }
Esempio n. 19
0
 internal void Copy( ECTime ToCopy )
 {
     // This won't be quite exact since it's to the nearest millisecond.
     UTCTime = new DateTime( ToCopy.GetYear(),
                     ToCopy.GetMonth(),
                     ToCopy.GetDay(),
                     ToCopy.GetHour(),
                     ToCopy.GetMinute(),
                     ToCopy.GetSecond(),
                     ToCopy.GetMillisecond(),
                     DateTimeKind.Utc ); // DateTimeKind.Local
 }
Esempio n. 20
0
        internal void UpdateHostNameCheckTime( string IP )
        {
            try
            {
            IPStatusRec StatusRec;
            if( IPsDictionary.ContainsKey( IP ))
              StatusRec = IPsDictionary[IP];
            else
              StatusRec = MakeNewStatusRec();

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            StatusRec.TimeIndex = RightNow.GetIndex();
            StatusRec.LastHostNameUpdate = RightNow.GetIndex();
            IPsDictionary[IP] = StatusRec;
            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in NetStatus.UpdateHostNameCheckTime():" );
              MForm.ShowStatus( Except.Message );
              }
        }
Esempio n. 21
0
        internal bool SendCrudeClientHello( RNGCryptoServiceProvider CryptoRand, CustomerTLSClient CustomerTLS )
        {
            try
            {
            int LengthOfOuterMessage = 52 - 5;
            byte[] ToSendBuf = new byte[LengthOfOuterMessage + 5];

            // The first five bytes are the outer TLS record.
            ToSendBuf[0] = 22; // Content type is Handshake
            ToSendBuf[1] = 3;  // Version Major   TLS version 1.2 is version 3.3 (of SSL).
            ToSendBuf[2] = 3;  // Version Minor
            ToSendBuf[3] = (byte)(LengthOfOuterMessage >> 8);
            ToSendBuf[4] = (byte)(LengthOfOuterMessage);

            // Start of the inner ClientHello message.
            ToSendBuf[5] = 1; // Message type 1 is a  ClientHello message.

            int LengthOfClientHelloMessage = LengthOfOuterMessage - 4;
            ToSendBuf[6] = (byte)(LengthOfClientHelloMessage >> 16);
            ToSendBuf[7] = (byte)(LengthOfClientHelloMessage >> 8);
            ToSendBuf[8] = (byte)(LengthOfClientHelloMessage);
            ToSendBuf[9] = 3;   // Version Major
            ToSendBuf[10] = 3;  // Version Minor

            // This part for Unix time is not in TLS 1.3 because there's no point in having it.
            // But it is here in TLS 1.2.
            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            ulong UnixTime = RightNow.ToUnixTime();
            ToSendBuf[11] = (byte)(UnixTime >> 24);
            ToSendBuf[12] = (byte)(UnixTime >> 16);
            ToSendBuf[13] = (byte)(UnixTime >> 8);
            ToSendBuf[14] = (byte)(UnixTime);

            // These bytes have to be cryptographically random.
            // These are used later in generating the master secret and keys, etc.
            byte[] RandomBytes = new byte[28];
            CryptoRand.GetBytes( RandomBytes );

            int Index = 15;
            for( int Count = 0; Count < 28; Count++ )
              {
              ToSendBuf[Index] = RandomBytes[Count];
              Index++;
              }

            // Index is 15 + 28 = 43.
            // StatusString += "Index at the end of Random bytes is: " + Index.ToString() + "\r\n";
            // Index at the end of Random bytes is: 43

            ToSendBuf[43] = 0; // Session ID Length is zero. It's not resuming a session here.

            // A browser sends a lot more cipher suites than this so this is
            // usually a lot longer.  The algorithm you prefer to use should
            // be listed first.  So they are listed in order of preference.
            ToSendBuf[44] = 0; // Cipher Suites Length high byte
            ToSendBuf[45] = 4; // Cipher Suites Length
            ToSendBuf[46] = 0;
            ToSendBuf[47] = 0x35; // TLS_RSA_WITH_AES_256_CBC_SHA    = { 0x00,0x35 };
            ToSendBuf[48] = 0;
            ToSendBuf[49] = 0x3D; // TLS_RSA_WITH_AES_256_CBC_SHA256 = { 0x00,0x3D };
            ToSendBuf[50] = 1; // Compression Methods Length
            ToSendBuf[51] = 0; // Compression Method is null.

            // This message has no extensions, so that's all there is to send.
            return CustomerTLS.SendBuffer( ToSendBuf );

            }
            catch( Exception Except )
              {
              StatusString += "Exception in SendCrudeClientHello()\r\n";
              StatusString += Except.Message + "\r\n";
              return false;
              }
        }
Esempio n. 22
0
        internal bool ClearMidnightValues()
        {
            try
            {
            // The IP stuff is also kept in the server log.
            ECTime RecTime = new ECTime();
            ECTime OldTime = new ECTime();
            OldTime.SetToNow();
            OldTime.AddMinutes( -(60 * 24 * 30)); // 30 days.
            ulong OldIndex = OldTime.GetIndex();

            SortedDictionary<string, IPStatusRec> TempIPsDictionary = new SortedDictionary<string, IPStatusRec>();

            foreach( KeyValuePair<string, IPStatusRec> Kvp in IPsDictionary )
              {
              RecTime.SetFromIndex( Kvp.Value.TimeIndex );
              if( RecTime.GetIndex() < OldIndex )
            continue;

              // Keep totals on things like bad reg key count.
              IPStatusRec Rec = Kvp.Value;
              Rec.TimedOutCount = 0;
              Rec.GoodWebRequestCount = 0;
              // TotalGoodWebRequestCount
              // BadWebPageCount
              Rec.GetPublicKeyCount = 0;
              // Rec.TotalGetPublicKeyCount
              Rec.ConfirmBillingCount = 0;
              // Rec.TotalConfirmBillingCount

              TempIPsDictionary[Kvp.Key] = Rec;
              }

            IPsDictionary = TempIPsDictionary;
            return true;

            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in ClearMidnightValues():" );
              MForm.ShowStatus( Except.Message );
              return false;
              }
        }
Esempio n. 23
0
        internal void ShowIPStatus()
        {
            ECTime RecTime = new ECTime();
            MForm.ShowStatus( " " );

            string ShowS = "IP Address\t" +
                   "Server Time\t" +
                   "Server Date\t" +
                   "Hacker Count\t" +
                   "Timed Out Count\t" +
                   "Bad Web Page Count\t" +
                   "Good Web Request Count\t" +
                   "Total Good Web Request Count\t" +
                   "Port 80 Count\t" +
                   "GetPublicKeyCount\t" +
                   "TotalGetPublicKeyCount\t" +
                   "ConfirmBillingCount\t" +
                   "TotalConfirmBillingCount\t" +
                   "Referrer\t" +
                   "User Agent\t" +
                   "Host Name\t" +
                   "Sent Text";

            MForm.ShowStatus( ShowS );

            int HowMany = 0;
            foreach( KeyValuePair<string, IPStatusRec> Kvp in IPsDictionary )
              {
              // Don't show too many.  This is only meant as a quick way to show
              // some records.
              HowMany++;
              if( HowMany > 1000 )
            {
            MForm.ShowStatus( " " );
            MForm.ShowStatus( "Can't show more than 1000 IPs." );
            MForm.ShowStatus( " " );
            return;
            }

              RecTime.SetFromIndex( Kvp.Value.TimeIndex );

              ShowS = Kvp.Key + "\t" +
             RecTime.ToLocalTimeString() + "\t" +
             RecTime.ToLocalDateString() + "\t" +
             Kvp.Value.HackerCount.ToString( "N0" ) + "\t" +
             Kvp.Value.TimedOutCount.ToString( "N0" ) + "\t" +
             Kvp.Value.BadWebPageCount.ToString( "N0" ) + "\t" +
             Kvp.Value.GoodWebRequestCount.ToString( "N0" ) + "\t" +
             Kvp.Value.TotalGoodWebRequestCount.ToString( "N0" ) + "\t" +
             Kvp.Value.Port80Count.ToString( "N0" ) + "\t" +
             Kvp.Value.Port443Count.ToString( "N0" ) + "\t" +
             Kvp.Value.GetPublicKeyCount.ToString( "N0" ) + "\t" +
             Kvp.Value.TotalGetPublicKeyCount.ToString( "N0" ) + "\t" +
             Kvp.Value.ConfirmBillingCount.ToString( "N0" ) + "\t" +
             Kvp.Value.TotalConfirmBillingCount.ToString( "N0" ) + "\t" +
             Utility.CleanAsciiString( Kvp.Value.Referer, 300 ) + "\t" +
             Utility.CleanAsciiString( Kvp.Value.UserAgent, 300 ) + "\t" +
             Utility.CleanAsciiString( Kvp.Value.HostName, 300 ) + "\t" +
             Utility.CleanAsciiString( Kvp.Value.SentText, 300 );

              MForm.ShowStatus( ShowS );
              }

            MForm.ShowStatus( " " );
        }
Esempio n. 24
0
        private void DoCRTTest( Integer StartingNumber )
        {
            CRTMath CRTMath1 = new CRTMath( Worker );
            ECTime CRTTestTime = new ECTime();
            ChineseRemainder CRTTest = new ChineseRemainder( IntMath );
            ChineseRemainder CRTTest2 = new ChineseRemainder( IntMath );
            ChineseRemainder CRTAccumulate = new ChineseRemainder( IntMath );
            ChineseRemainder CRTToTest = new ChineseRemainder( IntMath );
            ChineseRemainder CRTTempEqual = new ChineseRemainder( IntMath );
            ChineseRemainder CRTTestEqual = new ChineseRemainder( IntMath );
            Integer BigBase = new Integer();
            Integer ToTest = new Integer();
            Integer Accumulate = new Integer();
            Integer Test1 = new Integer();
            Integer Test2 = new Integer();

            CRTTest.SetFromTraditionalInteger( StartingNumber );
            // If the digit array size isn't set right in relation to
            // Integer.DigitArraySize then it can cause an error here.
            CRTMath1.GetTraditionalInteger( Accumulate, CRTTest );

            if( !Accumulate.IsEqual( StartingNumber ))
              throw( new Exception( "  !Accumulate.IsEqual( Result )." ));

            CRTTestEqual.SetFromTraditionalInteger( Accumulate );
            if( !CRTMath1.IsEqualToInteger( CRTTestEqual, Accumulate ))
              throw( new Exception( "IsEqualToInteger() didn't work." ));

            // Make sure it works with even numbers too.
            Test1.Copy( StartingNumber );
            Test1.SetD( 0, Test1.GetD( 0 ) & 0xFE );
            CRTTest.SetFromTraditionalInteger( Test1 );
            CRTMath1.GetTraditionalInteger( Accumulate, CRTTest );

            if( !Accumulate.IsEqual( Test1 ))
              throw( new Exception( "For even numbers.  !Accumulate.IsEqual( Test )." ));
            ////////////

            // Make sure the size of this works with the Integer size because
            // an overflow is hard to find.
            CRTTestTime.SetToNow();
            Test1.SetToMaxValueForCRT();
            CRTTest.SetFromTraditionalInteger( Test1 );
            CRTMath1.GetTraditionalInteger( Accumulate, CRTTest );

            if( !Accumulate.IsEqual( Test1 ))
              throw( new Exception( "For the max value. !Accumulate.IsEqual( Test1 )." ));

            // Worker.ReportProgress( 0, "CRT Max test seconds: " + CRTTestTime.GetSecondsToNow().ToString( "N1" ));
            // Worker.ReportProgress( 0, "MaxValue: " + IntMath.ToString10( Accumulate ));
            // Worker.ReportProgress( 0, "MaxValue.Index: " + Accumulate.GetIndex().ToString());

            // Multiplicative Inverse test:
            Integer TestDivideBy = new Integer();
            Integer TestProduct = new Integer();
            ChineseRemainder CRTTestDivideBy = new ChineseRemainder( IntMath );
            ChineseRemainder CRTTestProduct = new ChineseRemainder( IntMath );

            TestDivideBy.Copy( StartingNumber );
            TestProduct.Copy( StartingNumber );
            IntMath.Multiply( TestProduct, TestDivideBy );

            CRTTestDivideBy.SetFromTraditionalInteger( TestDivideBy );
            CRTTestProduct.SetFromTraditionalInteger( TestDivideBy );
            CRTTestProduct.Multiply( CRTTestDivideBy );

            CRTMath1.GetTraditionalInteger( Accumulate, CRTTestProduct );

            if( !Accumulate.IsEqual( TestProduct ))
              throw( new Exception( "Multiply test was bad." ));

            IntMath.Divide( TestProduct, TestDivideBy, Quotient, Remainder );
            if( !Remainder.IsZero())
              throw( new Exception( "This test won't work unless it divides it exactly." ));

            ChineseRemainder CRTTestQuotient = new ChineseRemainder( IntMath );
            CRTMath1.MultiplicativeInverse( CRTTestProduct, CRTTestDivideBy, CRTTestQuotient );

            // Yes, multiplicative inverse is the same number
            // as with regular division.
            Integer TestQuotient = new Integer();
            CRTMath1.GetTraditionalInteger( TestQuotient, CRTTestQuotient );
            if( !TestQuotient.IsEqual( Quotient ))
              throw( new Exception( "Modular Inverse in DoCRTTest didn't work." ));

            // Subtract
            Test1.Copy( StartingNumber );
            IntMath.SetFromString( Test2, "12345678901234567890123456789012345" );

            CRTTest.SetFromTraditionalInteger( Test1 );
            CRTTest2.SetFromTraditionalInteger( Test2 );

            CRTTest.Subtract( CRTTest2 );
            IntMath.Subtract( Test1, Test2 );

            CRTMath1.GetTraditionalInteger( Accumulate, CRTTest );

            if( !Accumulate.IsEqual( Test1 ))
              throw( new Exception( "Subtract test was bad." ));

            // Add
            Test1.Copy( StartingNumber );
            IntMath.SetFromString( Test2, "12345678901234567890123456789012345" );

            CRTTest.SetFromTraditionalInteger( Test1 );
            CRTTest2.SetFromTraditionalInteger( Test2 );

            CRTTest.Add( CRTTest2 );
            IntMath.Add( Test1, Test2 );

            CRTMath1.GetTraditionalInteger( Accumulate, CRTTest );

            if( !Accumulate.IsEqual( Test1 ))
              throw( new Exception( "Add test was bad." ));

            /////////
            CRTBaseMath CBaseMath = new CRTBaseMath( Worker, CRTMath1 );

            ChineseRemainder CRTInput = new ChineseRemainder( IntMath );
            CRTInput.SetFromTraditionalInteger( StartingNumber );

            Test1.Copy( StartingNumber );
            IntMath.SetFromString( Test2, "12345678901234567890123456789012345" );
            IntMath.Add( Test1, Test2 );

            Integer TestModulus = new Integer();
            TestModulus.Copy( Test1 );
            ChineseRemainder CRTTestModulus = new ChineseRemainder( IntMath );
            CRTTestModulus.SetFromTraditionalInteger( TestModulus );

            Integer Exponent = new Integer();
            Exponent.SetFromULong( PubKeyExponentUint );

            CBaseMath.ModularPower( CRTInput, Exponent, CRTTestModulus, false );
            IntMath.IntMathNew.ModularPower( StartingNumber, Exponent, TestModulus, false );

            if( !CRTMath1.IsEqualToInteger( CRTInput, StartingNumber ))
              throw( new Exception( "CRTBase ModularPower() didn't work." ));

            CRTBase ExpTest = new CRTBase( IntMath );
            CBaseMath.SetFromCRTNumber( ExpTest, CRTInput );
            CBaseMath.GetExponentForm( ExpTest, 37 );

            // Worker.ReportProgress( 0, "CRT was good." );
        }
Esempio n. 25
0
        internal void MakeRSAKeys()
        {
            int ShowBits = (PrimeIndex + 1) * 32;
            // int TestLoops = 0;

            Worker.ReportProgress( 0, "Making RSA keys." );
            Worker.ReportProgress( 0, "Bits size is: " + ShowBits.ToString());

            // ulong Loops = 0;
            while( true )
              {
              if( Worker.CancellationPending )
            return;

              Thread.Sleep( 1 ); // Give up the time slice.  Let other things on the server run.

              // Make two prime factors.
              // Normally you'd only make new primes when you pay the Certificate
              // Authority for a new certificate.
              if( !MakeAPrime( PrimeP, PrimeIndex, 20 ))
            return;

              IntegerBase TestP = new IntegerBase();
              IntegerBaseMath IntBaseMath = new IntegerBaseMath( IntMath );
              string TestS = IntMath.ToString10( PrimeP );
              IntBaseMath.SetFromString( TestP, TestS );
              string TestS2 = IntBaseMath.ToString10( TestP );
              if( TestS != TestS2 )
            throw( new Exception( "TestS != TestS2 for IntegerBase." ));

              if( Worker.CancellationPending )
            return;

              if( !MakeAPrime( PrimeQ, PrimeIndex, 20 ))
            return;

              if( Worker.CancellationPending )
            return;

              // This is extremely unlikely.
              Integer Gcd = new Integer();
              IntMath.GreatestCommonDivisor( PrimeP, PrimeQ, Gcd );
              if( !Gcd.IsOne())
            {
            Worker.ReportProgress( 0, "They had a GCD: " + IntMath.ToString10( Gcd ));
            continue;
            }

              if( Worker.CancellationPending )
            return;

              // This would never happen since the public key exponent used here
              // is one of the small primes in the array in IntegerMath that it
              // was checked against.  But it does show here in the code that
              // they have to be co-prime to each other.  And in the future it
              // might be found that the public key exponent has to be much larger
              // than the one used here.
              IntMath.GreatestCommonDivisor( PrimeP, PubKeyExponent, Gcd );
              if( !Gcd.IsOne())
            {
            Worker.ReportProgress( 0, "They had a GCD with PubKeyExponent: " + IntMath.ToString10( Gcd ));
            continue;
            }

              if( Worker.CancellationPending )
            return;

              IntMath.GreatestCommonDivisor( PrimeQ, PubKeyExponent, Gcd );
              if( !Gcd.IsOne())
            {
            Worker.ReportProgress( 0, "2) They had a GCD with PubKeyExponent: " + IntMath.ToString10( Gcd ));
            continue;
            }

              // For Modular Reduction.  This only has to be done
              // once, when P and Q are made.
              IntMathNewForP.SetupGeneralBaseArray( PrimeP );
              IntMathNewForQ.SetupGeneralBaseArray( PrimeQ );

              PrimePMinus1.Copy( PrimeP );
              IntMath.SubtractULong( PrimePMinus1, 1 );
              PrimeQMinus1.Copy( PrimeQ );
              IntMath.SubtractULong( PrimeQMinus1, 1 );

              // These checks should be more thorough.

              if( Worker.CancellationPending )
            return;

              Worker.ReportProgress( 0, "The Index of Prime P is: " + PrimeP.GetIndex().ToString() );
              Worker.ReportProgress( 0, "Prime P:" );
              Worker.ReportProgress( 0, IntMath.ToString10( PrimeP ));
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "Prime Q:" );
              Worker.ReportProgress( 0, IntMath.ToString10( PrimeQ ));
              Worker.ReportProgress( 0, " " );

              PubKeyN.Copy( PrimeP );
              IntMath.Multiply( PubKeyN, PrimeQ );

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "PubKeyN:" );
              Worker.ReportProgress( 0, IntMath.ToString10( PubKeyN ));
              Worker.ReportProgress( 0, " " );

              // Euler's Theorem:
              // https://en.wikipedia.org/wiki/Euler's_theorem
              // if x ≡ y (mod φ(n)),
              // then a^x ≡ a^y (mod n).

              // Euler's Phi function (aka Euler's Totient function) is calculated
              // next.

              // PhiN is made from the two factors: (P - 1)(Q - 1)
              // PhiN is: (P - 1)(Q - 1) = PQ - P - Q + 1
              // If I add (P - 1) to PhiN I get:
              // PQ - P - Q + 1 + (P - 1) = PQ - Q.
              // If I add (Q - 1) to that I get:
              // PQ - Q + (Q - 1) = PQ - 1.
              // (P - 1)(Q - 1) + (P - 1) + (Q - 1) = PQ - 1

              // If (P - 1) and (Q - 1) had a larger GCD then PQ - 1 would have
              // that same factor too.

              IntMath.GreatestCommonDivisor( PrimePMinus1, PrimeQMinus1, Gcd );
              Worker.ReportProgress( 0, "GCD of PrimePMinus1, PrimeQMinus1 is: " + IntMath.ToString10( Gcd ));

              if( !Gcd.IsULong())
            {
            Worker.ReportProgress( 0, "This GCD number is too big: " + IntMath.ToString10( Gcd ));
            continue;
            }
              else
            {
            ulong TooBig = Gcd.GetAsULong();
            // How big of a GCD is too big?
            if( TooBig > 1234567 )
              {
              // (P - 1)(Q - 1) + (P - 1) + (Q - 1) = PQ - 1
              Worker.ReportProgress( 0, "This GCD number is bigger than 1234567: " + IntMath.ToString10( Gcd ));
              continue;
              }
            }

              Integer Temp1 = new Integer();

              PhiN.Copy( PrimePMinus1 );
              Temp1.Copy( PrimeQMinus1 );
              IntMath.Multiply( PhiN, Temp1 );

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "PhiN:" );
              Worker.ReportProgress( 0, IntMath.ToString10( PhiN ));
              Worker.ReportProgress( 0, " " );
              if( Worker.CancellationPending )
            return;

              // In RFC 2437 there are commonly used letters/symbols to represent
              // the numbers used.  So the number e is the public exponent.
              // The number e that is used here is called PubKeyExponentUint = 65537.
              // In the RFC the private key d is the multiplicative inverse of
              // e mod PhiN.  Which is mod (P - 1)(Q - 1).  It's called
              // PrivKInverseExponent here.

              if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponent, PubKeyExponent, PhiN, Worker ))
            return;

              if( PrivKInverseExponent.IsZero())
            continue;

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "PrivKInverseExponent: " + IntMath.ToString10( PrivKInverseExponent ));

              if( Worker.CancellationPending )
            return;

              // In RFC 2437 it defines a number dP which is the multiplicative
              // inverse, mod (P - 1) of e.  That dP is named PrivKInverseExponentDP here.
              Worker.ReportProgress( 0, " " );
              if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponentDP, PubKeyExponent, PrimePMinus1, Worker ))
            return;

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "PrivKInverseExponentDP: " + IntMath.ToString10( PrivKInverseExponentDP ));
              if( PrivKInverseExponentDP.IsZero())
            continue;

              // PrivKInverseExponentDP is PrivKInverseExponent mod PrimePMinus1.
              Integer Test1 = new Integer();
              Test1.Copy( PrivKInverseExponent );
              IntMath.Divide( Test1, PrimePMinus1, Quotient, Remainder );
              Test1.Copy( Remainder );
              if( !Test1.IsEqual( PrivKInverseExponentDP ))
            throw( new Exception( "Bug. This does not match the definition of PrivKInverseExponentDP." ));

              if( Worker.CancellationPending )
            return;

              // In RFC 2437 it defines a number dQ which is the multiplicative
              // inverse, mod (Q - 1) of e.  That dQ is named PrivKInverseExponentDQ here.
              Worker.ReportProgress( 0, " " );
              if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponentDQ, PubKeyExponent, PrimeQMinus1, Worker ))
            return;

              if( PrivKInverseExponentDQ.IsZero())
            continue;

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "PrivKInverseExponentDQ: " + IntMath.ToString10( PrivKInverseExponentDQ ));
              if( Worker.CancellationPending )
            return;

              Test1.Copy( PrivKInverseExponent );
              IntMath.Divide( Test1, PrimeQMinus1, Quotient, Remainder );
              Test1.Copy( Remainder );
              if( !Test1.IsEqual( PrivKInverseExponentDQ ))
            throw( new Exception( "Bug. This does not match the definition of PrivKInverseExponentDQ." ));

              // Make a random number to test encryption/decryption.
              Integer ToEncrypt = new Integer();
              int HowManyBytes = PrimeIndex * 4;
              byte[] RandBytes = MakeRandomBytes( HowManyBytes );
              if( RandBytes == null )
            {
            Worker.ReportProgress( 0, "Error making random bytes in MakeRSAKeys()." );
            return;
            }

              if( !ToEncrypt.MakeRandomOdd( PrimeIndex - 1, RandBytes ))
            {
            Worker.ReportProgress( 0, "Error making random number ToEncrypt." );
            return;
            }

              Integer PlainTextNumber = new Integer();
              PlainTextNumber.Copy( ToEncrypt );

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "Before encrypting number: " + IntMath.ToString10( ToEncrypt ));
              Worker.ReportProgress( 0, " " );

              IntMath.IntMathNew.ModularPower( ToEncrypt, PubKeyExponent, PubKeyN, false );
              if( Worker.CancellationPending )
            return;

              Worker.ReportProgress( 0, IntMath.GetStatusString() );

              Integer CipherTextNumber = new Integer();
              CipherTextNumber.Copy( ToEncrypt );

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "Encrypted number: " + IntMath.ToString10( CipherTextNumber ));
              Worker.ReportProgress( 0, " " );

              ECTime DecryptTime = new ECTime();
              DecryptTime.SetToNow();
              IntMath.IntMathNew.ModularPower( ToEncrypt, PrivKInverseExponent, PubKeyN, false );
              Worker.ReportProgress( 0, "Decrypted number: " + IntMath.ToString10( ToEncrypt ));

              if( !PlainTextNumber.IsEqual( ToEncrypt ))
            {
            throw( new Exception( "PlainTextNumber not equal to unencrypted value." ));
            // Because P or Q wasn't really a prime?
            // Worker.ReportProgress( 0, "PlainTextNumber not equal to unencrypted value." );
            // continue;
            }

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "Decrypt time seconds: " + DecryptTime.GetSecondsToNow().ToString( "N2" ));
              Worker.ReportProgress( 0, " " );
              if( Worker.CancellationPending )
            return;

              // Test the standard optimized way of decrypting:
              if( !ToEncrypt.MakeRandomOdd( PrimeIndex - 1, RandBytes ))
            {
            Worker.ReportProgress( 0, "Error making random number in MakeRSAKeys()." );
            return;
            }

              PlainTextNumber.Copy( ToEncrypt );
              IntMath.IntMathNew.ModularPower( ToEncrypt, PubKeyExponent, PubKeyN, false );
              if( Worker.CancellationPending )
            return;

              CipherTextNumber.Copy( ToEncrypt );

              // QInv is the multiplicative inverse of PrimeQ mod PrimeP.
              if( !IntMath.MultiplicativeInverse( PrimeQ, PrimeP, QInv, Worker ))
            throw( new Exception( "MultiplicativeInverse() returned false." ));

              if( QInv.IsNegative )
            throw( new Exception( "This is a bug. QInv is negative." ));

              Worker.ReportProgress( 0, "QInv is: " + IntMath.ToString10( QInv ));

              DecryptWithQInverse( CipherTextNumber,
                           ToEncrypt, // Decrypt it to this.
                           PlainTextNumber, // Test it against this.
                           PubKeyN,
                           PrivKInverseExponentDP,
                           PrivKInverseExponentDQ,
                           PrimeP,
                           PrimeQ,
                           Worker );

              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, "Found the values:" );
              Worker.ReportProgress( 0, "Seconds: " + StartTime.GetSecondsToNow().ToString( "N0" ));
              Worker.ReportProgress( 0, " " );

              Worker.ReportProgress( 1, "Prime1: " + IntMath.ToString10( PrimeP ));
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 1, "Prime2: " + IntMath.ToString10( PrimeQ ));
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 1, "PubKeyN: " + IntMath.ToString10( PubKeyN ));
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 1, "PrivKInverseExponent: " + IntMath.ToString10( PrivKInverseExponent ));

              /*
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, " " );
              Worker.ReportProgress( 0, " " );
              DoCRTTest( PrivKInverseExponent );
              Worker.ReportProgress( 0, "Finished CRT test." );
              Worker.ReportProgress( 0, " " );
              */

              return; // Comment this out to just leave it while( true ) for testing.
              }
        }
Esempio n. 26
0
        internal void AddToConfirmBillingCount( string Address )
        {
            try
            {
            IPStatusRec StatusRec;
            if( IPsDictionary.ContainsKey( Address ))
              StatusRec = IPsDictionary[Address];
            else
              StatusRec = MakeNewStatusRec();

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            StatusRec.TimeIndex = RightNow.GetIndex();
            StatusRec.ConfirmBillingCount++;
            StatusRec.TotalConfirmBillingCount++;

            IPsDictionary[Address] = StatusRec;
            }
            catch( Exception Except )
              {
              MForm.ShowStatus( "Exception in AddToConfirmBillingCount():" );
              MForm.ShowStatus( Except.Message );
              }
        }
Esempio n. 27
0
        internal bool FindTwoFactorsWithFermat( Integer Product, Integer P, Integer Q, ulong MinimumX )
        {
            ECTime StartTime = new ECTime();
            StartTime.SetToNow();

            Integer TestSqrt = new Integer();
            Integer TestSquared = new Integer();
            Integer SqrRoot = new Integer();

            TestSquared.Copy( Product );
            IntMath.Multiply( TestSquared, Product );
            IntMath.SquareRoot( TestSquared, SqrRoot );
            TestSqrt.Copy( SqrRoot );
            IntMath.DoSquare( TestSqrt );
            // IntMath.Multiply( TestSqrt, SqrRoot );
            if( !TestSqrt.IsEqual( TestSquared ))
              throw( new Exception( "The square test was bad." ));

            // Some primes:
            // 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
            // 101, 103, 107

            P.SetToZero();
            Q.SetToZero();
            Integer TestX = new Integer();
            SetupQuadResArray( Product );

            ulong BaseTo37 = QuadResBigBase * 29UL * 31UL * 37UL;
            // ulong BaseTo31 = QuadResBigBase * 29UL * 31UL;
            ulong ProdModTo37 = IntMath.GetMod64( Product, BaseTo37 );
            // ulong ProdModTo31 = IntMath.GetMod64( Product, BaseTo31 );
            for( ulong BaseCount = 0; BaseCount < (29 * 31 * 37); BaseCount++ )
              {
              if( (BaseCount & 0xF) == 0 )
            Worker.ReportProgress( 0, "Find with Fermat BaseCount: " + BaseCount.ToString() );

              if( Worker.CancellationPending )
            return false;

              ulong Base = (BaseCount + 1) * QuadResBigBase; // BaseCount times 223,092,870.
              if( Base < MinimumX )
            continue;

              Base = BaseCount * QuadResBigBase; // BaseCount times 223,092,870.
              for( uint Count = 0; Count < QuadResArrayLast; Count++ )
            {
            // The maximum CountPart can be is just under half the size of
            // the Product. (Like if Y - X was equal to 1, and Y + X was
            // equal to the Product.)  If it got anywhere near that big it
            // would be inefficient to try and find it this way.
            ulong CountPart = Base + QuadResArray[Count];
            ulong Test = ProdModTo37 + (CountPart * CountPart);
            // ulong Test = ProdModTo31 + (CountPart * CountPart);
            Test = Test % BaseTo37;
            // Test = Test % BaseTo31;
            if( !IntegerMath.IsQuadResidue29( Test ))
              continue;

            if( !IntegerMath.IsQuadResidue31( Test ))
              continue;

            if( !IntegerMath.IsQuadResidue37( Test ))
              continue;

            ulong TestBytes = (CountPart & 0xFFFFF);
            TestBytes *= (CountPart & 0xFFFFF);
            ulong ProdBytes = Product.GetD( 1 );
            ProdBytes <<= 8;
            ProdBytes |= Product.GetD( 0 );

            uint FirstBytes = (uint)(TestBytes + ProdBytes);
            if( !IntegerMath.FirstBytesAreQuadRes( FirstBytes ))
              {
              // Worker.ReportProgress( 0, "First bytes aren't quad res." );
              continue;
              }

            TestX.SetFromULong( CountPart );
            IntMath.MultiplyULong( TestX, CountPart );
            TestX.Add( Product );

            // uint Mod37 = (uint)IntMath.GetMod32( TestX, 37 );
            // if( !IntegerMath.IsQuadResidue37( Mod37 ))
              // continue;

            // Do more of these tests with 41, 43, 47...
            // if( !IntegerMath.IsQuadResidue41( Mod37 ))
              // continue;

            // Avoid doing this square root at all costs.
            if( IntMath.SquareRoot( TestX, SqrRoot ))
              {
              Worker.ReportProgress( 0, " " );
              if( (CountPart & 1) == 0 )
            Worker.ReportProgress( 0, "CountPart was even." );
              else
            Worker.ReportProgress( 0, "CountPart was odd." );

              // Found an exact square root.
              // P + (CountPart * CountPart) = Y*Y
              // P = (Y + CountPart)Y - CountPart)

              P.Copy( SqrRoot );
              Integer ForSub = new Integer();
              ForSub.SetFromULong( CountPart );
              IntMath.Subtract( P, ForSub );

              // Make Q the bigger one and put them in order.
              Q.Copy( SqrRoot );
              Q.AddULong( CountPart );

              if( P.IsOne() || Q.IsOne())
            {
            // This happens when testing with small primes.
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, "Went all the way to 1 in FindTwoFactorsWithFermat()." );
            Worker.ReportProgress( 0, " " );
            Worker.ReportProgress( 0, " " );
            P.SetToZero(); // It has no factors.
            Q.SetToZero();
            return true; // Tested everything, so it's a prime.
            }

              Worker.ReportProgress( 0, "Found P: " + IntMath.ToString10( P ) );
              Worker.ReportProgress( 0, "Found Q: " + IntMath.ToString10( Q ) );
              Worker.ReportProgress( 0, "Seconds: " + StartTime.GetSecondsToNow().ToString( "N1" ));
              Worker.ReportProgress( 0, " " );
              throw( new Exception( "Testing this." ));
              // return true; // With P and Q.
              }
            // else
              // Worker.ReportProgress( 0, "It was not an exact square root." );

            }
              }

            // P and Q would still be zero if it never found them.
            return false;
        }
Esempio n. 28
0
        internal void StartSendingForDns( string IP )
        {
            if( MForm.GetIsClosing())
              return;

            if( IsDisposed )
              return;

            ulong LastUpdate = MForm.NetStats.GetLastHostNameUpdate( IP );
            if( LastUpdate != 0 )
              {
              ECTime LastUpdateTime = new ECTime( LastUpdate );
              if( LastUpdateTime.GetDaysToNow() < 7 )
            return;

              }
            // MForm.ServerLog.AddToLog( "Description Data", "Getting description data." );

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            MForm.NetStats.UpdateHostNameCheckTime( IP );

            // ShowStatus( " " );
            // ShowStatus( "Dns for: " + IP + " " + ForWhat + " " + RightNow.ToLocalTimeString() );
            // ShowStatus( "Dns for: " + ForWhat + " " + RightNow.ToLocalTimeString() );

            DnsWorkerInfo WInfo = new DnsWorkerInfo();

            WInfo.IP = IP;

            try
            {
            if( !DNSBackgroundWorker.IsBusy )
              {
              DNSBackgroundWorker.RunWorkerAsync( WInfo );
              }
            else
              {
              // ShowStatus( "Dns background process is busy." );
              }

            }
            catch( Exception Except )
              {
              ShowStatus( "Error starting background process for Dns." );
              ShowStatus( Except.Message );
              return;
              }
        }
Esempio n. 29
0
        private void CheckTimer_Tick(object sender, EventArgs e)
        {
            // This timer event only gets called when the server isn't otherwise busy.
            // Even though the timer interval is set to once every 50 milliseconds it
            // doesn't mean it will get called that often.
            // It has TestTime to check on how busy it is.

            if( !IsEnabled )
              return;

            CheckTimer.Stop();
            try // for finally
            {

            try // for catch
            {
            ECTime TestTime = new ECTime();
            TestTime.SetToNow();

            // 100 clients queued up per timer tick is 2,000 per second max,
            // assuming the server isn't busy and the timer events get called that often.
            // But if there were that many clients connecting you'd need more front end
            // servers to handle the I/O.  Or it's a denial of service attack, and you'd
            // need to deal with that.
            for( int Count = 0; Count < 100; Count++ )
              {
              if( !IsEnabled )
            return;

              if( Listener.Pending() )
            QueueConnectedClient();
              else
            break;

              }

            CloseTimedOut();
            if( !IsEnabled )
              return;

            FreeClosed();
            if( !IsEnabled )
              return;

            ProcessOuterMessages();
            if( !IsEnabled )
              return;

            double Seconds = TestTime.GetSecondsToNow();
            if( Seconds > 1.0 )
              {
              ShowStatus( " " );
              ShowStatus( "**************************************************" );
              ShowStatus( "TLS Listener Test time seconds: " + Seconds.ToString( "N0" ));
              ShowStatus( "Test time:: " + TestTime.ToLocalTimeString());
              ShowStatus( "**************************************************" );
              ShowStatus( " " );
              }
            }
            catch( Exception Except )
              {
              ShowStatus( "Exception in CheckTimerTick: \r\n" + Except.Message );
              return;
              }

            }
            finally
              {
              CheckTimer.Start();
              }
        }
Esempio n. 30
0
        private void ProcessWebRequests()
        {
            if( MForm.GetIsClosing())
              return;

            ECTime RightNow = new ECTime();
            RightNow.SetToNow();
            for( int Count = 0; Count < ClientsLast; Count++ )
              {
              if( Clients[Count] == null ) // This should never happen but...
            continue;

              // If this is something that has already been processed.
              if( Clients[Count].GetProcessingStarted())
            continue;

              // IsShutDown is a little slower than the above checks.
              if( Clients[Count].IsShutDown())
            continue;

              if( !Clients[Count].IsBrowserRequest())
            continue;

              if( !Clients[Count].IsBrowserRequestReady())
            continue;

              // ShowStatus( "Got a browser request 2." );

              Clients[Count].SetProcessingStarted( true );

              string InputS = Utility.GetCleanUnicodeString( Clients[Count].GetAllInputS(), 2000 );

              // This FileName is already cleaned ASCII.
              string FileName = Clients[Count].GetHTTPFileRequested();
              string OriginalFileName = FileName;

              FileName = FileName.ToLower();
              FileName = FileName.Replace( "/", "" );
              // ShowStatus( "FileName is: " + FileName );

              if( FileName.StartsWith( "bad http:" ))
            {
            MForm.NetStats.AddToHackerCount( Clients[Count].GetRemoteAddress(), InputS );
            // MForm.ServerLog.AddToLog( "Bad HTTP", InputS, Clients[Count].GetRemoteAddress() );
            Clients[Count].FreeEverything();
            ShowStatus( FileName );
            continue;
            }

              if( FileName.StartsWith( "hacking:" ))
            {
            DailyHackCount++;
            MForm.NetStats.AddToHackerCount( Clients[Count].GetRemoteAddress(), InputS );
            // MForm.ServerLog.AddToLog( "Hacking", InputS, Clients[Count].GetRemoteAddress() );
            Clients[Count].FreeEverything();
            RightNow.SetToNow();
            ShowStatus( RightNow.ToLocalTimeString() + " on " + RightNow.ToLocalDateString() );
            ShowStatus( FileName );
            ShowStatus( " " );
            continue;
            }

              RightNow.SetToNow();
              string Referer = "None";
              string UserAgent = "None";

              if( FileName == "laplata.htm" )
            {
            if( MForm.GetIsClosing())
              return;

            // MForm.NetStats.AddTo...

            byte[] ToSendBuf = MForm.LaPlataData1.GetHTML( "smith" );
            if( ToSendBuf != null )
              Clients[Count].SendGenericWebResponse( ToSendBuf, RightNow.GetIndex(), UniqueEntityTag, "text/html" );

            Referer = Clients[Count].GetReferer();
            UserAgent = Clients[Count].GetUserAgent();
            // MForm.ServerLog.AddToLog() ...
            continue;
            }

              if( !MForm.WebFData.ContainsFile( FileName ))
            {
            Clients[Count].FreeEverything();
             // This is already clean ASCII.
            string LogText = FileName + ": " + InputS;
            // MForm.ServerLog.AddToLog( "No Web File", LogText, Clients[Count].GetRemoteAddress() );
            MForm.NetStats.AddToBadWebPageCount( Clients[Count].GetRemoteAddress(), InputS );
            ShowStatus( " " );
            RightNow.SetToNow();
            ShowStatus( RightNow.ToLocalTimeString() + " on " + RightNow.ToLocalDateString() );
            ShowStatus( "No Web File" );
            ShowStatus( "Original: " + OriginalFileName );
            ShowStatus( "Fixed: " + FileName );
            ShowStatus( "From IP: " + Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName.EndsWith( ".exe" ) || FileName.EndsWith( ".apk" ))
            {
            ShowStatus( " " );
            RightNow.SetToNow();
            ShowStatus( RightNow.ToLocalTimeString() + " on " + RightNow.ToLocalDateString() );
            ShowStatus( "Request for: " + FileName );
            ShowStatus( "From IP: " + Clients[Count].GetRemoteAddress() );
            ShowStatus( " " );
            }

              Referer = Clients[Count].GetReferer();
              UserAgent = Clients[Count].GetUserAgent();
              MForm.NetStats.AddToUserAgentAndReferer( Clients[Count].GetRemoteAddress(), Referer, UserAgent );

              // Increment UniqueEntityTag when it sends something.
              UniqueEntityTag++;
              // FileName is already clean ASCII, it's lower case, and trimmed.

              // This is a reference to the buffer, but the client copies from it.
              byte[] Buffer = MForm.WebFData.GetBuffer( FileName );
              if( Buffer == null )
            {
            ShowStatus( "The buffer was null for a good web request: " + FileName );
            continue;
            }

              if( FileName.EndsWith( ".jpg" ))
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "image/jpeg" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName.EndsWith( ".gif" ))
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "image/gif" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName.EndsWith( ".htm" ))
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "text/html" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName.EndsWith( ".txt" ))
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "text/plain" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName.EndsWith( ".pdf" ))
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "application/pdf" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              if( FileName == "favicon.ico" )
            {
            Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "image/vnd.microsoft.icon" );
            // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
            continue;
            }

              // Default to sending text unless there's some other way to send it.
              Clients[Count].SendGenericWebResponse( Buffer, RightNow.GetIndex(), UniqueEntityTag, "text/plain" );
              // MForm.ServerLog.AddToLog( "Finished Web Request", FileName, Clients[Count].GetRemoteAddress() );
              }
        }