コード例 #1
0
        public string GetUniqueHashedId()
        {
            // Get unique device ID
            var query = new SecRecord(SecKind.GenericPassword);

            query.Service = NSBundle.MainBundle.BundleIdentifier;
            query.Account = "UniqueID";

            NSData uniqueId = SecKeyChain.QueryAsData(query);

            if (uniqueId != null)
            {
                // Get it hashed
                var hashedId = GetSha256HashForId(uniqueId.ToString());
                return(hashedId);
            }
            else
            {
                query.ValueData = NSData.FromString(System.Guid.NewGuid().ToString());
                var err = SecKeyChain.Add(query);
                if (err != SecStatusCode.Success && err != SecStatusCode.DuplicateItem)
                {
                    throw new Exception("Cannot store Unique ID");
                }
                var hashedValueData = GetSha256HashForId(query.ValueData.ToString());

                return(hashedValueData);
            }
        }
コード例 #2
0
        public override Task <SecureFingerprintAuthenticationResult> NativeSecureAuthenticateAsync(AuthenticationRequestConfiguration authRequestConfig, string key, CancellationToken cancellationToken)
        {
            TaskCompletionSource <SecureFingerprintAuthenticationResult> response = new TaskCompletionSource <SecureFingerprintAuthenticationResult>();
            var securityRecord = new SecRecord(SecKind.GenericPassword)
            {
                Service = key
            };

            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                SecStatusCode status;
                NSData resultData = SecKeyChain.QueryAsData(securityRecord, false, out status);

                var result      = resultData != null ? new NSString(resultData, NSStringEncoding.UTF8) : "";
                var secResponse = new SecureFingerprintAuthenticationResult()
                {
                    ErrorMessage = "",
                    SecureData   = new Dictionary <string, string> {
                        { key, result }
                    },
                    Status = MapStatus(status)
                };

                if (status == SecStatusCode.VerifyFailed)
                {
                    //Todo: check if this is the correct status code when a finger print has been added or removed
                    throw new FingerprintStoreInvalidatedException();
                }
            });

            return(response.Task);
        }
コード例 #3
0
        public string GetIdentifier()
        {
            var query = new SecRecord(SecKind.GenericPassword);

            query.Service = NSBundle.MainBundle.BundleIdentifier;
            query.Account = "UniqueID";

            NSData uniqueId = SecKeyChain.QueryAsData(query);

            if (uniqueId == null)
            {
                query.ValueData = NSData.FromString(System.Guid.NewGuid().ToString());
                var err = SecKeyChain.Add(query);
                if (err != SecStatusCode.Success && err != SecStatusCode.DuplicateItem)
                {
                    throw new Exception("Cannot store Unique ID");
                }

                return(query.ValueData.ToString());
            }
            else
            {
                return(uniqueId.ToString());
            }
        }
コード例 #4
0
        static Epitech.Intra.SharedApp.Security.Credit GetItem()
        {
            var securityRecord = new SecRecord(SecKind.GenericPassword)
            {
                Service            = "com.Epitech.uIntra",
                UseOperationPrompt = "Authentifier pour vous connecter à l'Intranet"
            };

            SecStatusCode status;
            NSData        resultData = null;

            UIApplication.SharedApplication.InvokeOnMainThread(() => {
                resultData = SecKeyChain.QueryAsData(securityRecord, false, out status);
            });

            var result = resultData != null ? new NSString(resultData, NSStringEncoding.UTF8) : null;

            if (result == null)
            {
                return(null);
            }
            else
            {
                char[]   sep    = { '|' };
                string[] credit = ((string)result).Split(sep);
                return(new Epitech.Intra.SharedApp.Security.Credit {
                    Login = credit [0], Password = credit [1]
                });
            }
        }
コード例 #5
0
        public static string RetrieveKeychain(string message)
        {
            if (IsiPhone4Or4S())
            {
                message = "";
            }

            var query = new SecRecord(SecKind.GenericPassword)
            {
                Service            = NSBundle.MainBundle.BundleIdentifier,
                Account            = "SecurityViewAccount",
                AccessControl      = new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence),
                UseOperationPrompt = message,
            };


            SecStatusCode status;

            var res = SecKeyChain.QueryAsData(query, false, out status);

            if (res != null)
            {
                return(NSString.FromData(res, NSStringEncoding.Unicode).ToString());
            }

            return(null);
        }
コード例 #6
0
        //a simple way to generate and persist unique id for ios device using keychain. This unique id won't change even if app is uninstalled and re-installed.
        //only for devices pre ios 6 (from here: http://david-smith.org/iosversionstats/, only < 5% devices)
        private string UniqueID()
        {
            var query = new SecRecord(SecKind.GenericPassword);

            query.Service = NSBundle.MainBundle.BundleIdentifier;
            query.Account = "UniqueID";

            NSData uniqueId = SecKeyChain.QueryAsData(query);

            if (uniqueId == null)
            {
                query.ValueData = NSData.FromString(System.Guid.NewGuid().ToString());
                var err = SecKeyChain.Add(query);
                if (err != SecStatusCode.Success && err != SecStatusCode.DuplicateItem)
                {
                    logger.i("IOSDeviceService", "Failed to save unique id", null);
                }

                return(query.ValueData.ToString());
            }
            else
            {
                return(uniqueId.ToString());
            }
        }
コード例 #7
0
        /// <summary>
        /// Real KeyChain Method
        /// </summary>
        /// <returns>The key chain password.</returns>
        /// <param name="account">Account.</param>
        public string GetKeyChainPassword(string account)
        {
            var query = new SecRecord(SecKind.InternetPassword)
            {
                Server           = "com.crosshelper.cycbis",
                Service          = "com.crosshelper.cycbis",
                Account          = account,
                ApplicationLabel = "Cycbis"
            };
            var password = SecKeyChain.QueryAsData(query).ToString();

            return(password);
        }
コード例 #8
0
        public void QueryAsDataArray()
        {
            SecStatusCode code;
            SecRecord     queryRec = new SecRecord(SecKind.GenericPassword)
            {
                Service = RecordService,
                Account = RecordAccount,
            };
            var data = SecKeyChain.QueryAsData(queryRec, true, 1, out code);

            if (code == SecStatusCode.Success && queryRec != null)
            {
                Assert.NotNull(data [0].Bytes);
            }
        }
コード例 #9
0
        public void QueryAsDataArray()
        {
            SecStatusCode code;
            SecRecord     queryRec = new SecRecord(SecKind.GenericPassword)
            {
                Service = "KEYCHAIN_SERVICE",
                Label   = "KEYCHAIN_SERVICE",
                Account = "KEYCHAIN_ACCOUNT"
            };
            var data = SecKeyChain.QueryAsData(queryRec, true, 1, out code);

            if (code == SecStatusCode.Success && queryRec != null)
            {
                Assert.NotNull(data [0].Bytes);
            }
        }
コード例 #10
0
        internal static byte[] GetRawBrokerKey(ICoreLogger logger)
        {
            byte[]    brokerKey = null;
            SecRecord record    = new SecRecord(SecKind.GenericPassword)
            {
                Generic     = NSData.FromString(iOSBrokerConstants.LocalSettingsContainerName),
                Service     = iOSBrokerConstants.BrokerKeyService,
                Account     = iOSBrokerConstants.BrokerKeyAccount,
                Label       = iOSBrokerConstants.BrokerKeyLabel,
                Comment     = iOSBrokerConstants.BrokerKeyComment,
                Description = iOSBrokerConstants.BrokerKeyStorageDescription
            };

            NSData key = SecKeyChain.QueryAsData(record);

            if (key == null)
            {
                AesManaged algo = new AesManaged();
                algo.GenerateKey();
                byte[] rawBytes = algo.Key;
                NSData byteData = NSData.FromArray(rawBytes);
                record = new SecRecord(SecKind.GenericPassword)
                {
                    Generic     = NSData.FromString(iOSBrokerConstants.LocalSettingsContainerName),
                    Service     = iOSBrokerConstants.BrokerKeyService,
                    Account     = iOSBrokerConstants.BrokerKeyAccount,
                    Label       = iOSBrokerConstants.BrokerKeyLabel,
                    Comment     = iOSBrokerConstants.BrokerKeyComment,
                    Description = iOSBrokerConstants.BrokerKeyStorageDescription,
                    ValueData   = byteData
                };

                var result = SecKeyChain.Add(record);
                if (result != SecStatusCode.Success)
                {
                    logger.Info(iOSBrokerConstants.FailedToSaveBrokerKey + result);
                }

                brokerKey = byteData.ToArray();
            }
            else
            {
                brokerKey = key.ToArray();
            }

            return(brokerKey);
        }
        internal static byte[] GetRawBrokerKey()
        {
            byte[]    brokerKey = null;
            SecRecord record    = new SecRecord(SecKind.GenericPassword)
            {
                Generic     = NSData.FromString(LocalSettingsContainerName),
                Service     = "Broker Key Service",
                Account     = "Broker Key Account",
                Label       = "Broker Key Label",
                Comment     = "Broker Key Comment",
                Description = "Storage for broker key"
            };

            NSData key = SecKeyChain.QueryAsData(record);

            if (key == null)
            {
                AesManaged algo = new AesManaged();
                algo.GenerateKey();
                byte[] rawBytes = algo.Key;
                NSData byteData = NSData.FromArray(rawBytes);
                record = new SecRecord(SecKind.GenericPassword)
                {
                    Generic     = NSData.FromString(LocalSettingsContainerName),
                    Service     = "Broker Key Service",
                    Account     = "Broker Key Account",
                    Label       = "Broker Key Label",
                    Comment     = "Broker Key Comment",
                    Description = "Storage for broker key",
                    ValueData   = byteData
                };

                var result = SecKeyChain.Add(record);
                if (result != SecStatusCode.Success)
                {
                    CallState.Default.Logger.Warning(null, "Failed to save broker key: " + result);
                }

                brokerKey = byteData.ToArray();
            }
            else
            {
                brokerKey = key.ToArray();
            }

            return(brokerKey);
        }
コード例 #12
0
        //
        // EXPERIMENTAL
        // Needs some more testing before we can make this public.
        // AppleTls does not actually use this API, so it may be removed again.
        //
        internal NSData GetPublicKey()
        {
            if (handle == IntPtr.Zero)
            {
                throw new ObjectDisposedException("SecCertificate");
            }

            var policy = SecPolicy.CreateBasicX509Policy();
            var trust  = new SecTrust(this, policy);

            trust.Evaluate();

            SecStatusCode status;

            using (var key = trust.GetPublicKey())
                using (var query = new SecRecord(SecKind.Key)) {
                    query.SetValueRef(key);

                    status = SecKeyChain.Add(query);
                    if (status != SecStatusCode.Success && status != SecStatusCode.DuplicateItem)
                    {
                        throw new InvalidOperationException(status.ToString());
                    }

                    bool added = status == SecStatusCode.Success;

                    try {
                        var data = SecKeyChain.QueryAsData(query, false, out status);
                        if (status != SecStatusCode.Success)
                        {
                            throw new InvalidOperationException(status.ToString());
                        }

                        return(data);
                    } finally {
                        if (added)
                        {
                            status = SecKeyChain.Remove(query);
                            if (status != SecStatusCode.Success)
                            {
                                throw new InvalidOperationException(status.ToString());
                            }
                        }
                    }
                }
        }
        private static bool TryGetBrokerKey(out byte[] brokerKey)
        {
            SecRecord record = new SecRecord(SecKind.GenericPassword)
            {
                Generic = NSData.FromString(iOSBrokerConstants.LocalSettingsContainerName),
                Account = iOSBrokerConstants.BrokerKeyAccount,
                Service = iOSBrokerConstants.BrokerKeyService
            };

            NSData key = SecKeyChain.QueryAsData(record);

            if (key != null)
            {
                brokerKey = key.ToArray();
                return(true);
            }

            brokerKey = null;
            return(false);
        }
コード例 #14
0
        void CopyMatchingAsync()
        {
            var securityRecord = new SecRecord(SecKind.GenericPassword)
            {
                Service            = Text.SERVICE_NAME,
                UseOperationPrompt = Text.AUTHENTICATE_TO_ACCESS_SERVICE_PASSWORD
            };

            DispatchQueue.MainQueue.DispatchAsync(() => {
                SecStatusCode status;
                NSData resultData = SecKeyChain.QueryAsData(securityRecord, false, out status);

                var result = resultData != null ? new NSString(resultData, NSStringEncoding.UTF8) : Text.USER_CANCELED_ACTION;

                var sb = new StringBuilder();
                sb.AppendFormat(Text.SEC_ITEM_COPY_MATCHING_STATUS, status.GetDescription());
                sb.AppendFormat(Text.RESULT, result);
                PrintResult(textView, sb.ToString());
            });
        }
コード例 #15
0
        public string Unprotect(string key)
        {
            var existingRecord = new SecRecord(SecKind.GenericPassword)
            {
                Account = key,
                Service = NSBundle.MainBundle.BundleIdentifier
            };

            // Locate the entry in the keychain, using the label, service and account information.
            // The result code will tell us the outcome of the operation.
            SecStatusCode resultCode;

            string str  = null;
            NSData find = SecKeyChain.QueryAsData(existingRecord);

            if (find != null)
            {
                str = find.ToString();
            }
            return(str);
        }
コード例 #16
0
        public byte[] GetBytes(string key)
        {
            byte[] result = null;

            var record = new SecRecord(SecKind.GenericPassword)
            {
                Account = key, Service = Service
            };
            var loadedData = SecKeyChain.QueryAsData(record, false, out var status);

            if (status == SecStatusCode.Success)
            {
                result = loadedData.ToArray();
            }
            else if (status != SecStatusCode.ItemNotFound)
            {
                throw new InvalidOperationException($"Failed to get from keychain. (status={status})");
            }

            return(result);
        }
コード例 #17
0
        private bool IsExists(SecRecord record)
        {
            var data = SecKeyChain.QueryAsData(record, false, out var status);

            return(status == SecStatusCode.Success && data.Length > 0);
        }
コード例 #18
0
        public void AddConfig()
        {
            // The password for the VPN connection, add this to Keychain
            var password = new SecRecord(SecKind.GenericPassword)
            {
                Service   = "Password Service",
                ValueData = NSData.FromString("MY_PASSWORD", NSStringEncoding.UTF8),
                Generic   = NSData.FromString("VPNPas", NSStringEncoding.UTF8),
            };

            // The query for the VPN password. Use this to find the password in Keychain
            var queryPassword = new SecRecord(SecKind.GenericPassword)
            {
                Service = "Password Service",
                Generic = NSData.FromString("VPNPas", NSStringEncoding.UTF8),
            };

            // The shared secret for the VPN connection, add this to Keychain
            var secret = new SecRecord(SecKind.GenericPassword)
            {
                Service   = "Secret Service",
                ValueData = NSData.FromString("hide.io", NSStringEncoding.UTF8),
                Generic   = NSData.FromString("secret", NSStringEncoding.UTF8),
            };

            // The query for the VPN shared secret. Use this to find the shared secret in Keychain
            var querySecret = new SecRecord(SecKind.GenericPassword)
            {
                Service = "Secret Service",
                Generic = NSData.FromString("secret", NSStringEncoding.UTF8),
            };

            // First remove old Keychain entries, then add the new ones
            // Just for testing purposes: this is to make sure the keychain entries are correct
            var err = SecKeyChain.Remove(queryPassword);

            Console.WriteLine("Password remove: " + err);

            err = SecKeyChain.Remove(querySecret);
            Console.WriteLine("Secret remove: " + err);

            err = SecKeyChain.Add(password);
            Console.WriteLine("Password add: " + err);

            err = SecKeyChain.Add(secret);
            Console.WriteLine("Secret add: " + err);


            manager.LoadFromPreferences(error => {
                if (error != null)
                {
                    Console.WriteLine("Error loading preferences: ");
                    Console.WriteLine(error);
                }
                else
                {
                    NEVpnProtocol p = null;

                    // IKEv2 Protocol
                    NEVpnProtocolIke2 ike2    = new NEVpnProtocolIke2();
                    ike2.AuthenticationMethod = NEVpnIkeAuthenticationMethod.None;
                    //	ike2.LocalIdentifier = "";
                    ike2.RemoteIdentifier          = "hide.me";
                    ike2.UseExtendedAuthentication = true;
                    ike2.DisconnectOnSleep         = false;

                    // ipSec Protocol
                    NEVpnProtocolIpSec ipSec        = new NEVpnProtocolIpSec();
                    ipSec.AuthenticationMethod      = NEVpnIkeAuthenticationMethod.SharedSecret;
                    ipSec.UseExtendedAuthentication = true;
                    ipSec.DisconnectOnSleep         = false;
                    SecStatusCode res;

                    // Set the shared secret reference for ipSec:
                    // 1) Search for the secret in keychain and retrieve it as a persistent reference
                    // 2) Set the found secret to SharedSecretReference if the secret was found
                    var match = SecKeyChain.QueryAsData(querySecret, true, out res);
                    if (res == SecStatusCode.Success)
                    {
                        Console.WriteLine("Secret found, setting secret...");
                        ipSec.SharedSecretReference = match;
                    }
                    else
                    {
                        Console.WriteLine("Could not set secret:");
                        Console.WriteLine(res);
                    }

                    // Set the protocol to IKEv2 or ipSec
                    //		p = ike2;
                    p = ipSec;

                    // Set Accountname, Servername and description
                    p.Username      = "******";
                    p.ServerAddress = "free-nl.hide.me";
                    manager.LocalizedDescription = "hide.me VPN";

                    // Set the password reference for the protocol:
                    // 1) Search for the password in keychain and retrieve it as a persistent reference
                    // 2) Set the found password to PasswordReference if the secret was found
                    match = SecKeyChain.QueryAsData(queryPassword, true, out res);
                    if (res == SecStatusCode.Success)
                    {
                        Console.WriteLine("Password found, setting password...");
                        p.PasswordReference = match;
                    }
                    else
                    {
                        Console.WriteLine(res);
                    }
                    manager.OnDemandEnabled = false;

                    // Set the managers protocol and save it to the iOS custom VPN preferences
                    manager.ProtocolConfiguration = p;
                    manager.SaveToPreferences(error2 => {
                        if (error2 != null)
                        {
                            Console.WriteLine("Could not save VPN preferences");
                            Console.WriteLine(error2.DebugDescription);
                        }
                    });
                }
            });
        }