/// <summary>
        /// Calls the authentication callback handler.
        /// </summary>
        /// -
        /// <param name="e">An instance of <see cref="T:InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs"/>
        /// containing the details of the authentication callback.
        /// </param>
        protected virtual void OnAuthentication(BluetoothWin32AuthenticationEventArgs e)
        {
            EventHandler <BluetoothWin32AuthenticationEventArgs> callback = m_userCallback;

            if (callback != null)
            {
                m_userCallback(this, e);
            }
        }
 internal BluetoothWin32AuthenticationEventArgs(int errorCode, BluetoothWin32AuthenticationEventArgs previousEa)
 {
     if (previousEa == null)
     {
         throw new ArgumentNullException("previousEa");
     }
     m_device         = previousEa.Device;
     _authIoCapa      = previousEa._authIoCapa;
     _authMethod      = previousEa._authMethod;
     _authReq         = previousEa._authReq;
     _numberOrPasskey = previousEa._numberOrPasskey;
     m_attemptNumber  = previousEa.AttemptNumber + 1;
     //
     m_errorCode = errorCode;
 }
        private int BluetoothSendAuthenticationResponseExOob(ref BLUETOOTH_DEVICE_INFO bdi,
                                                             bool?confirm, BluetoothWin32AuthenticationEventArgs e)
        {
            if (!confirm.HasValue)
            {
                return(NativeErrorSuccess);
            }
            Int32 ret;
            var   rsp = new BLUETOOTH_AUTHENTICATE_RESPONSE__OOB_DATA_INFO();

            rsp.negativeResponse = 1; // Default to NEGATIVE, really set below.
            rsp.authMethod       = e.AuthenticationMethod;
            if (!(e.AuthenticationMethod == BluetoothAuthenticationMethod.OutOfBand))
            {
                Debug.Fail("Bad call!!! method is: " + e.AuthenticationMethod);
                return(NativeErrorNotAuthenticated);
            }
            rsp.bthAddressRemote = bdi.Address;
            switch (confirm)
            {
            case true:
                rsp.negativeResponse = 0;
                // Set the oob values
                // (Testing shows that P/Invoke disallowed only incorrect
                // lengthinline arrays, null arrays are ok).
                if (e.OobC != null)
                {
                    rsp.oobInfo.C = e.OobC;
                }
                if (e.OobR != null)
                {
                    rsp.oobInfo.R = e.OobR;
                }
                break;

            case false:
            case null:
                Debug.Assert(confirm != null, "Should have exited above when non-response.");
                rsp.negativeResponse = 1;
                break;
            }
            ret = NativeMethods.BluetoothSendAuthenticationResponseEx(
                m_radioHandle, ref rsp);
            return(ret);
        }
Exemplo n.º 4
0
 void Win32AuthCallbackTwoSeparateAuthenticationsHandler(Object sender, InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs e)
 {
     console.WriteLine("Authenticating {0} {1}", e.Device.DeviceAddress, e.Device.DeviceName);
     console.WriteLine("  Attempt# {0}, Last error code {1}", e.AttemptNumber, e.PreviousNativeErrorCode);
     //
     if (Win32AuthCallbackTwoSeparateAuthentications_count == 0)
     {
         e.Pin = "1234";
     }
     else if (Win32AuthCallbackTwoSeparateAuthentications_count == 1)
     {
         e.Pin = "9876";
     }
     else if (Win32AuthCallbackTwoSeparateAuthentications_count == 2)
     {
         e.Pin = "ásdfghjkl";
     }
     console.WriteLine("Using '{0}'", e.Pin);
     Win32AuthCallbackTwoSeparateAuthentications_count += 1;
 }
Exemplo n.º 5
0
        void Win32AuthCallbackJohoHandler(Object sender, InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs e)
        {
            String address = e.Device.DeviceAddress.ToString();

            console.WriteLine("Received an authentication request from address " + address);

            //compare the first 8 hex numbers, this is just a special case because in the
            //used scenario the model of the devices can be identified by the first 8 hex
            //numbers, the last 4 numbers being the device specific part.
            if (address.Substring(0, 8).Equals("0099880D") ||
                address.Substring(0, 8).Equals("0099880E"))
            {
                //send authentication response
                e.Pin = "5276";
            }
            else if (address.Substring(0, 8).Equals("00997788"))
            {
                //send authentication response
                e.Pin = "1423";
            }
        }
Exemplo n.º 6
0
        void Win32AuthCallbackInitialBadPasscodeAndRetryHandler(Object sender, InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs e)
        {
            console.WriteLine("Authenticating {0} {1}", e.Device.DeviceAddress, e.Device.DeviceName);
            console.WriteLine("  Attempt# {0}, Last error code {1}", e.AttemptNumber, e.PreviousNativeErrorCode);
            if (e.AttemptNumber != Win32AuthCallbackInitialBadPasscodeAndRetry_count)
            {
                console.WriteLine("Bad AttemptNumber!!!");
            }
            Random rnd         = new Random();
            String badPasscode = rnd.NextDouble().ToString();

            badPasscode = badPasscode.Substring(0, Math.Min(16, badPasscode.Length));
            //
            if (Win32AuthCallbackInitialBadPasscodeAndRetry_count == 0 ||
                Win32AuthCallbackInitialBadPasscodeAndRetry_count == 1)
            {
                e.Pin = badPasscode;
                e.CallbackWithResult = true;
            }
            else if (Win32AuthCallbackInitialBadPasscodeAndRetry_count == 2 ||
                     Win32AuthCallbackInitialBadPasscodeAndRetry_count == 3)
            {
                e.Pin = "9876";
                e.CallbackWithResult = true;
            }
            else if (Win32AuthCallbackInitialBadPasscodeAndRetry_count == 4)
            {
                e.CallbackWithResult = true; //Try to *wrongly* get another callback!
            }
            else
            {
                console.WriteLine("Unexpected callback #{0}", Win32AuthCallbackInitialBadPasscodeAndRetry_count);
            }
            console.WriteLine("Using '{0}'", (e.Pin == null ? "<null>" : e.Pin));
            Win32AuthCallbackInitialBadPasscodeAndRetry_count += 1;
        }
 internal BluetoothWin32AuthenticationEventArgs(int errorCode, BluetoothWin32AuthenticationEventArgs previousEa)
 {
     if (previousEa == null) {
         throw new ArgumentNullException("previousEa");
     }
     m_device = previousEa.Device;
     m_attemptNumber = previousEa.AttemptNumber + 1;
     //
     m_errorCode = errorCode;
 }
 /// <summary>
 /// Calls the authentication callback handler.
 /// </summary>
 /// -
 /// <param name="e">An instance of <see cref="T:InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs"/> 
 /// containingthe details of the authentication callback.
 /// </param>
 protected virtual void OnAuthentication(BluetoothWin32AuthenticationEventArgs e)
 {
     EventHandler<BluetoothWin32AuthenticationEventArgs> callback = m_userCallback;
     if (callback != null) {
         m_userCallback(this, e);
     }
 }
 //--------------------------------------------------------------
 private bool NativeCallback(IntPtr param, ref BLUETOOTH_DEVICE_INFO bdi)
 {
     System.Diagnostics.Debug.Assert(m_pin == null ^ m_userCallback == null);
     //
     System.Diagnostics.Debug.WriteLine(String.Format(
             System.Globalization.CultureInfo.InvariantCulture,
             "AuthenticateResponder callback (for {0}): 0x{1:X} 0x{2:X}",
             m_remoteAddress, param, bdi.Address));
     //
     String pin;
     Int32 ret = NativeErrorSuccess;
     if (m_pin != null) {
         // Pre-specified case.
         System.Diagnostics.Debug.Assert(bdi.Address == m_remoteAddress.ToInt64(),
             "Should only get callback for the single device.");
         //TODO if (bdi.Address != m_remoteAddress.ToInt64()) {
         //    return false;
         //}
         pin = m_pin;
         ret = NativeMethods.BluetoothSendAuthenticationResponse(
             m_radioHandle, ref bdi, pin);
     } else {
         // Callback case.
         System.Diagnostics.Debug.Assert(m_userCallback != null);
         BluetoothWin32AuthenticationEventArgs e = new BluetoothWin32AuthenticationEventArgs(bdi);
         while (true) {
             // Callback the user code
             OnAuthentication(e);
             // Don't proceed if no (null) passcode given, or
             // if the last attempt was successful, or
             // the decvice has disppeared.
             if (e.Pin == null) {
                 break;
             }
             if (e.PreviousNativeErrorCode == NativeErrorSuccess && e.AttemptNumber != 0) {
                 break;
             }
             if (e.PreviousNativeErrorCode == NativeErrorDeviceNotConnected) {
                 // When I try this (against Win2k+Belkin and iPaq hx2190,
                 // both apparently with Broadcom) I see:
                 //[[
                 //Authenticate one device -- with wrong passcode here the first two times.
                 //Passcode respectively: 'BAD-x', 'BAD-y', '9876'
                 //Making PC discoverable
                 //Hit Return to complete
                 //Authenticating 0017E464CF1E wm_alan1
                 //  Attempt# 0, Last error code 0
                 //Using '0.23672947484847'
                 //Authenticating 0017E464CF1E wm_alan1
                 //  Attempt# 1, Last error code 1244
                 //Using '0.54782851764365'
                 //Authenticating 0017E464CF1E wm_alan1
                 //  Attempt# 2, Last error code 1167
                 //Using '9876'
                 //Authenticating 0017E464CF1E wm_alan1
                 //  Attempt# 3, Last error code 1167
                 //etc
                 //]]
                 // That is we see the error code of 1244=ErrorNotAuthenticated
                 // once, and then the peer device disappears (1167=ErrorDeviceNotConnected).
                 // I suppose that's a security feature -- its stops an attacker
                 // from trying again and again with different passcodes.
                 //
                 // Anyway the result of that is that is it NOT worth repeating
                 // the callback after the device disappears.
                 break;
             }
             pin = e.Pin;
             System.Diagnostics.Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                 "BW32Auth SendAuthRsp pin {0}", pin));
             ret = NativeMethods.BluetoothSendAuthenticationResponse(
                 m_radioHandle, ref bdi, pin);
             if (ret != NativeErrorSuccess) {
                 System.Diagnostics.Trace.WriteLine(String.Format(
                     System.Globalization.CultureInfo.InvariantCulture,
                     "    BluetoothSendAuthenticationResponse failed: {0}=0x{0:X}", ret));
             }
             // Have to callback the user code after the attempt?
             BluetoothWin32AuthenticationEventArgs lastEa = e;
             if (!lastEa.CallbackWithResult) {
                 break;
             }
             e = new BluetoothWin32AuthenticationEventArgs(ret, lastEa);
         }
     }
     //
     if (ret != NativeErrorSuccess) {
         System.Diagnostics.Trace.WriteLine(String.Format(
             System.Globalization.CultureInfo.InvariantCulture,
             "BluetoothSendAuthenticationResponse failed: {0}=0x{0:X}", ret));
     }
     return true; // "The return value from this function is ignored by the system."
 }
Exemplo n.º 10
0
        private int BluetoothSendAuthenticationResponseExNumCompPasskey(ref BLUETOOTH_DEVICE_INFO bdi,
                                                                        bool?confirm, BluetoothWin32AuthenticationEventArgs e)
        {
            if (!confirm.HasValue)
            {
                return(NativeErrorSuccess);
            }
            Int32 ret;
            var   rsp = new BLUETOOTH_AUTHENTICATE_RESPONSE__NUMERIC_COMPARISON_PASSKEY_INFO();

            rsp.negativeResponse = 1; // Default to NEGATIVE, really set below.
            rsp.authMethod       = e.AuthenticationMethod;
            if (!(e.AuthenticationMethod == BluetoothAuthenticationMethod.NumericComparison ||
                  e.AuthenticationMethod == BluetoothAuthenticationMethod.Passkey ||
                  e.AuthenticationMethod == BluetoothAuthenticationMethod.PasskeyNotification))
            {
                Debug.Fail("Bad call!!! method is: " + e.AuthenticationMethod);
                return(NativeErrorNotAuthenticated);
            }
            rsp.bthAddressRemote = bdi.Address;
            switch (confirm)
            {
            case true:
                rsp.negativeResponse = 0;
                // Set the response number/passcode value
                if (e.ResponseNumberOrPasskey.HasValue)
                {
                    rsp.numericComp_passkey = checked ((uint)e.ResponseNumberOrPasskey.Value);
                }
                break;

            case false:
            case null:
                Debug.Assert(confirm != null, "Should have exited above when non-response.");
                rsp.negativeResponse = 1;
                break;
            }
            ret = NativeMethods.BluetoothSendAuthenticationResponseEx(
                m_radioHandle, ref rsp);
            return(ret);
        }
Exemplo n.º 11
0
        private bool NativeCallback(BluetoothAuthenticationMethod method,
                                    IntPtr param, ref BLUETOOTH_DEVICE_INFO bdi, bool versionEx,
                                    ref BLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS?pAuthCallbackParams)
        {
            System.Diagnostics.Debug.Assert(m_pin == null ^ m_userCallback == null);
            //
            System.Diagnostics.Debug.WriteLine(String.Format(
                                                   System.Globalization.CultureInfo.InvariantCulture,
                                                   "AuthenticateResponder callback (for {0}): 0x{1:X} 0x{2:X}",
                                                   m_remoteAddress, param, bdi.Address));
            //
            String pin;
            Int32  ret;

            if (m_pin != null)
            {
                // Pre-specified case.
                System.Diagnostics.Debug.Assert(bdi.Address == m_remoteAddress.ToInt64(),
                                                "Should only get callback for the single device.");
                //TODO if (bdi.Address != m_remoteAddress.ToInt64()) {
                //    return false;
                //}
                pin = m_pin;
                if (versionEx)
                {
                    // TODO Want to send a positive response here to NumericComparison??
                    ret = BluetoothSendAuthenticationResponseExPin(ref bdi, pin);
                }
                else
                {
                    ret = NativeMethods.BluetoothSendAuthenticationResponse(
                        m_radioHandle, ref bdi, pin);
                }
            }
            else if (method == BluetoothAuthenticationMethod.Legacy)
            {
                // Callback case.
                System.Diagnostics.Debug.Assert(m_userCallback != null);
                BluetoothWin32AuthenticationEventArgs e
                    = new BluetoothWin32AuthenticationEventArgs(bdi);
                while (true)
                {
                    // Callback the user code
                    OnAuthentication(e);
                    // Don't proceed if no (null) passcode given, or
                    // if the last attempt was successful, or
                    // the decvice has disppeared.
                    if (e.Pin == null)
                    {
                        ret = NativeErrorSuccess;
                        break;
                    }
                    if (e.PreviousNativeErrorCode == NativeErrorSuccess && e.AttemptNumber != 0)
                    {
                        Debug.Assert(e.CallbackWithResult, "NOT CbWR but here (A#)!!");
                        ret = NativeErrorSuccess;
                        break;
                    }
                    if (e.PreviousNativeErrorCode == NativeErrorDeviceNotConnected)
                    {
                        Debug.Assert(e.CallbackWithResult, "NOT CbWR but here (DNC)!!");
                        // When I try this (against Win2k+Belkin and iPaq hx2190,
                        // both apparently with Broadcom) I see:
                        //[[
                        //Authenticate one device -- with wrong passcode here the first two times.
                        //Passcode respectively: 'BAD-x', 'BAD-y', '9876'
                        //Making PC discoverable
                        //Hit Return to complete
                        //Authenticating 0017E464CF1E wm_alan1
                        //  Attempt# 0, Last error code 0
                        //Using '0.23672947484847'
                        //Authenticating 0017E464CF1E wm_alan1
                        //  Attempt# 1, Last error code 1244
                        //Using '0.54782851764365'
                        //Authenticating 0017E464CF1E wm_alan1
                        //  Attempt# 2, Last error code 1167
                        //Using '9876'
                        //Authenticating 0017E464CF1E wm_alan1
                        //  Attempt# 3, Last error code 1167
                        //etc
                        //]]
                        // That is we see the error code of 1244=ErrorNotAuthenticated
                        // once, and then the peer device disappears (1167=ErrorDeviceNotConnected).
                        // I suppose that's a security feature -- its stops an attacker
                        // from trying again and again with different passcodes.
                        //
                        // Anyway the result of that is that is it NOT worth repeating
                        // the callback after the device disappears.
                        ret = NativeErrorSuccess;
                        break;
                    }
                    pin = e.Pin;
                    System.Diagnostics.Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                     "BW32Auth SendAuthRsp pin {0}", pin));
                    if (versionEx)
                    {
                        ret = BluetoothSendAuthenticationResponseExPin(ref bdi, pin);
                    }
                    else
                    {
                        ret = NativeMethods.BluetoothSendAuthenticationResponse(
                            m_radioHandle, ref bdi, pin);
                    }
                    if (ret != NativeErrorSuccess)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format(
                                                               System.Globalization.CultureInfo.InvariantCulture,
                                                               "    BluetoothSendAuthenticationResponse failed: {0}=0x{0:X}", ret));
                    }
                    // Have to callback the user code after the attempt?
                    BluetoothWin32AuthenticationEventArgs lastEa = e;
                    if (!lastEa.CallbackWithResult)
                    {
                        break;
                    }
                    e = new BluetoothWin32AuthenticationEventArgs(ret, lastEa);
                }
            }
            else if (method == BluetoothAuthenticationMethod.NumericComparison ||
                     method == BluetoothAuthenticationMethod.Passkey ||
                     method == BluetoothAuthenticationMethod.PasskeyNotification ||
                     method == BluetoothAuthenticationMethod.OutOfBand
                     )
            {
                // Callback case.
                System.Diagnostics.Debug.Assert(m_userCallback != null);
                BluetoothWin32AuthenticationEventArgs e
                    = new BluetoothWin32AuthenticationEventArgs(bdi, ref pAuthCallbackParams);
                while (true)
                {
                    // Callback the user code
                    OnAuthentication(e);
                    // Check if after e.CallbackWithResult...
                    if (e.PreviousNativeErrorCode == NativeErrorSuccess && e.AttemptNumber != 0)
                    {
                        Debug.Assert(e.CallbackWithResult, "NOT CbWR but here (A#)!!");
                        ret = NativeErrorSuccess;
                        break;
                    }
                    if (e.PreviousNativeErrorCode == NativeErrorDeviceNotConnected)
                    {
                        Debug.Assert(e.CallbackWithResult, "NOT CbWR but here (DNC)!!");
                        ret = NativeErrorSuccess;
                        break;
                    }
                    bool?confirm = e.Confirm;
                    System.Diagnostics.Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                     "BW32Auth SendAuthRspEx-NumComparison {0}", confirm));
                    if (confirm == null)
                    {
                        ret = NativeErrorSuccess;
                        break;
                    }
                    if (method != BluetoothAuthenticationMethod.OutOfBand)
                    {
                        ret = BluetoothSendAuthenticationResponseExNumCompPasskey(ref bdi, confirm, e);
                    }
                    else
                    {
                        ret = BluetoothSendAuthenticationResponseExOob(ref bdi, confirm, e);
                    }
                    if (ret != NativeErrorSuccess)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format(
                                                               System.Globalization.CultureInfo.InvariantCulture,
                                                               "    BluetoothSendAuthenticationResponseEx failed: {0}=0x{0:X}", ret));
                    }
                    // Have to callback the user code after the attempt?
                    BluetoothWin32AuthenticationEventArgs lastEa = e;
                    if (!lastEa.CallbackWithResult)
                    {
                        break;
                    }
                    e = new BluetoothWin32AuthenticationEventArgs(ret, lastEa);
                }
            }
            else
            {
                Debug.Fail("Unsupported auth method: " + method);
                ret = NativeErrorSuccess;
            }
            //
            if (ret != NativeErrorSuccess)
            {
                System.Diagnostics.Trace.WriteLine(String.Format(
                                                       System.Globalization.CultureInfo.InvariantCulture,
                                                       "BluetoothSendAuthenticationResponse failed: {0}=0x{0:X}", ret));
            }
            return(true); // "The return value from this function is ignored by the system."
        }
Exemplo n.º 12
0
 private void AuthenticationHandler(object o, BluetoothWin32AuthenticationEventArgs e)
 {
     //all attempts to pair with this machine should raise this event
     System.Diagnostics.Debug.WriteLine(e.Device);
     System.Diagnostics.Debug.WriteLine(e.Pin);
     e.Pin = "1234";
 }
Exemplo n.º 13
0
 void AuthHandler(object sender, InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs e)
 {
     InTheHand.Net.Sockets.BluetoothDeviceInfo bdi = e.Device;
 }
Exemplo n.º 14
0
        void HandlerWithMsgBoxInclSsp(object sender, InTheHand.Net.Bluetooth.BluetoothWin32AuthenticationEventArgs e)
        {
            HndlrNoRespond(sender, e);
            if (e.AuthenticationMethod == BluetoothAuthenticationMethod.Legacy)
            {
                var line = console.ReadLine("Device with address " + e.Device.DeviceAddress.ToString()
                                            + " is wanting to pair."
                                            + " Please enter the PIN/passphrase.");
                if (line != null)
                {
                    e.Pin = line;
                }
            }
            else if (e.JustWorksNumericComparison == true)
            {
                var rslt = console.ReadYesNo("Allow device with address " + e.Device.DeviceAddress.ToString()
                                             + " to pair?", false);
                if (rslt)
                {
                    e.Confirm = true;
                }
            }
            else if (e.AuthenticationMethod == BluetoothAuthenticationMethod.NumericComparison)
            {
                var rslt = console.ReadYesNo("Device with address " + e.Device.DeviceAddress.ToString()
                                             + " is wanting to pair."
                                             + " Confirm that it is displaying this six-digit number on screen: "
                                             + e.NumberOrPasskeyAsString, false);
                if (rslt)
                {
                    e.Confirm = true;
                }
            }
            else if (e.AuthenticationMethod == BluetoothAuthenticationMethod.Passkey)
            {
                var line = console.ReadLine("Device with address " + e.Device.DeviceAddress.ToString()
                                            + " is wanting to pair."
                                            + " Please enter the six digit number that it is displaying on the other device's screen.");
                if (line != null)
                {
                    int pk;
                    if (Int32.TryParse(line, out pk) && pk >= 0 && pk < 1000000)
                    {
                        e.ResponseNumberOrPasskey = pk;
                        e.Confirm = true;
                    }
                    else
                    {
                        console.WriteLine("Invalid format Passkey entered.");
                    }
                }
            }
            else if (e.AuthenticationMethod == BluetoothAuthenticationMethod.PasskeyNotification)
            {
                var rslt = console.ReadYesNo("Device with address " + e.Device.DeviceAddress.ToString()
                                             + " is wanting to pair."
                                             // Please type this passkey on the other device...
                                             + " Confirm this Passkey on the other machine: "
                                             + e.NumberOrPasskeyAsString, false);
                if (rslt)
                {
                    e.Confirm = true;
                }
            }
            else if (e.AuthenticationMethod == BluetoothAuthenticationMethod.OutOfBand)
            {
                console.WriteLine("What to do with authentication method " + e.AuthenticationMethod + "??");
            }
            else
            {
                console.WriteLine("Unknown authentication method: " + e.AuthenticationMethod);
            }
            var callbackWithResult = console.ReadYesNo("Callback with Result", true);

            e.CallbackWithResult = callbackWithResult;
        }