Ejemplo n.º 1
0
        public void AddQueryRemove_Identity()
        {
            using (SecRecord rec = new SecRecord(SecKind.Identity))
                using (var id = IdentityTest.GetIdentity()) {
                    rec.SetValueRef(id);
                    SecStatusCode code = SecKeyChain.Add(rec);
                    Assert.True(code == SecStatusCode.DuplicateItem || code == SecStatusCode.Success);
                }

            if (!TestRuntime.CheckXcodeVersion(5, 0))
            {
                Assert.Inconclusive("QueryAsConcreteType does not work before iOS7");
            }

            using (SecRecord rec = new SecRecord(SecKind.Identity)) {
                SecStatusCode code;
                var           match = SecKeyChain.QueryAsConcreteType(rec, out code);
                if ((match == null) && (code == SecStatusCode.ItemNotFound))
                {
                    Assert.Inconclusive("Test randomly fails (race condition between addtion/commit/query?");
                }

                Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord-2");
                Assert.NotNull(match, "match-2");

                code = SecKeyChain.Remove(rec);
                Assert.That(code, Is.EqualTo(SecStatusCode.Success), "Remove");

                match = SecKeyChain.QueryAsConcreteType(rec, out code);
                Assert.That(code, Is.EqualTo(SecStatusCode.ItemNotFound), "QueryAsRecord-3");
                Assert.Null(match, "match-3");
            }
        }
Ejemplo n.º 2
0
        void AuthenticationType(SecAuthenticationType type)
        {
            var rec = new SecRecord(SecKind.InternetPassword)
            {
                Account = "AuthenticationType"
            };

            SecKeyChain.Remove(rec);              // it might already exists (or not)

            rec = new SecRecord(SecKind.InternetPassword)
            {
                Account            = "AuthenticationType",
                ValueData          = NSData.FromString("Password"),
                AuthenticationType = type,
                Server             = "www.xamarin.com"
            };

            Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add");

            SecStatusCode code;
            var           match = SecKeyChain.QueryAsRecord(rec, out code);

            Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord");

            Assert.That(match.AuthenticationType, Is.EqualTo(type), "AuthenticationType");
        }
Ejemplo n.º 3
0
        void Accessible(SecAccessible access)
        {
            var rec = new SecRecord(SecKind.GenericPassword)
            {
                Account = "Username"
            };

            SecKeyChain.Remove(rec);              // it might already exists (or not)

            rec = new SecRecord(SecKind.GenericPassword)
            {
                Account    = "Username",
                ValueData  = NSData.FromString("Password"),
                Accessible = access
            };

            Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add");

            SecStatusCode code;
            var           match = SecKeyChain.QueryAsRecord(rec, out code);

            Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord");

            Assert.That(match.Accessible, Is.EqualTo(access), "Accessible");
        }
        public static void SetValueForKey(string value, string key)
        {
            var record = ExistingRecordForKey(key);

            if (string.IsNullOrEmpty(value))
            {
                if (!string.IsNullOrEmpty(ValueForKey(key)))
                {
                    RemoveRecord(record);
                }

                return;
            }

            // if the key already exists, remove it
            if (!string.IsNullOrEmpty(ValueForKey(key)))
            {
                RemoveRecord(record);
            }

            var result = SecKeyChain.Add(CreateRecordForNewKeyValue(key, value));

            if (result != SecStatusCode.Success)
            {
                Console.WriteLine("Couldn't add record to keychain");
            }
        }
Ejemplo n.º 5
0
        string AttemptGetDeviceId()
        {
            var record = new SecRecord(SecKind.GenericPassword)
            {
                Generic = NSData.FromString(uniqueRecordName)
            };

            SecStatusCode securityStatusCode;

            var recordMatch = SecKeyChain.QueryAsRecord(record, out securityStatusCode);

            if (securityStatusCode == SecStatusCode.Success)
            {
                return(recordMatch.ValueData.ToString());
            }
            else
            {
                var newRecord = new SecRecord(SecKind.GenericPassword)
                {
                    ValueData = NSData.FromString(Guid.NewGuid().ToString()),
                    Generic   = NSData.FromString(uniqueRecordName)
                };
                SecKeyChain.Add(newRecord);
                return(newRecord.ValueData.ToString());
            }
        }
Ejemplo n.º 6
0
        public string GetIdentifier()
        {
            string serial = string.Empty;
            var    rec    = new SecRecord(SecKind.GenericPassword)
            {
                Generic = NSData.FromString("uidNumber")
            };

            SecStatusCode res;
            var           match = SecKeyChain.QueryAsRecord(rec, out res);

            if (res == SecStatusCode.Success)
            {
                serial = match.ValueData.ToString();
            }
            else
            {
                var uidNumberRecord = new SecRecord(SecKind.GenericPassword)
                {
                    Label     = "uid",
                    ValueData = NSData.FromString(Guid.NewGuid().ToString()),
                    Generic   = NSData.FromString("uidNumber")
                };

                var err = SecKeyChain.Add(uidNumberRecord);
                serial = uidNumberRecord.ValueData.ToString();
            }

            return(serial);
        }
        public async Task Save(Account account)
        {
            if (string.IsNullOrWhiteSpace(account.ServiceId))
            {
                throw new Exception("serviceId must be set.");
            }

            var data = JsonConvert.SerializeObject(account.Properties);

            var secRecord = new SecRecord(SecKind.GenericPassword)
            {
                Account    = account.Username,
                Service    = account.ServiceId,
                ValueData  = NSData.FromString(data, NSStringEncoding.UTF8),
                Accessible = SecAccessible.AfterFirstUnlockThisDeviceOnly
            };

            var old = await Find(account.ServiceId);

            if (old == null)
            {
                var statusCode = SecKeyChain.Add(secRecord);

                return;
            }

            SecKeyChain.Update(old, secRecord);
        }
    public void Save(string pin, string serviceId)
    {
        var statusCode        = SecStatusCode.Success;
        var serializedAccount = pin;
        var data = NSData.FromString(serializedAccount, NSStringEncoding.UTF8);
        //
        // Remove any existing record
        //
        var existing = FindAccount(serviceId);

        if (existing != null)
        {
            var query = new SecRecord(SecKind.GenericPassword);
            query.Service = serviceId;
            statusCode    = SecKeyChain.Remove(query);
            if (statusCode != SecStatusCode.Success)
            {
                throw new Exception("Could not save account to KeyChain: " + statusCode);
            }
        }
        //
        // Add this record
        //
        var record = new SecRecord(SecKind.GenericPassword);

        record.Service    = serviceId;
        record.Generic    = data;
        record.Accessible = SecAccessible.WhenUnlocked;
        statusCode        = SecKeyChain.Add(record);
        if (statusCode != SecStatusCode.Success)
        {
            throw new Exception("Could not save account to KeyChain: " + statusCode);
        }
    }
Ejemplo n.º 9
0
        public void Save(Core.Model.Account account)
        {
            SecStatusCode res;

            var match = this.QueryAsRecord(out res);

            if (res == SecStatusCode.Success)
            {
                // Update
                match.Generic   = account.SerializeToNSData();
                match.Account   = account.UserName;
                match.ValueData = NSData.FromString(account.Token);
                SecKeyChain.Update(Query, match);
            }
            else
            {
                // create
                res = SecKeyChain.Add(new SecRecord(SecKind.GenericPassword)
                {
                    Label     = AppResources.ApplicationTitle,
                    Account   = account.UserName,
                    Service   = Service,
                    ValueData = NSData.FromString(account.Token),
                    Generic   = account.SerializeToNSData()
                });

                if (res != SecStatusCode.Success)
                {
                    throw new Exception("Unable to save account data");
                }
            }
        }
Ejemplo n.º 10
0
        void AuthenticationType(SecAuthenticationType type)
        {
            var rec = new SecRecord(SecKind.InternetPassword)
            {
                Account = "AuthenticationType"
            };

            SecKeyChain.Remove(rec);              // it might already exists (or not)

            rec = new SecRecord(SecKind.InternetPassword)
            {
                Account            = $"{CFBundle.GetMain ().Identifier}-{GetType ().FullName}-{Process.GetCurrentProcess ().Id}",
                ValueData          = NSData.FromString("Password"),
                AuthenticationType = type,
                Server             = "www.xamarin.com"
            };

            Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add");

            var query = new SecRecord(SecKind.InternetPassword)
            {
                Account            = rec.Account,
                AuthenticationType = rec.AuthenticationType,
                Server             = rec.Server,
            };

            SecStatusCode code;
            var           match = SecKeyChain.QueryAsRecord(query, out code);

            Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord");

            Assert.That(match.AuthenticationType, Is.EqualTo(type), "AuthenticationType");
        }
Ejemplo n.º 11
0
        public void ServiceCallBack(ServiceCallbackHelper data)
        {
            if (data.Status == "error")
            {
                UIAlertView error = new UIAlertView("Ошибка", "Вы неправильно ввели логин или пароль.Попробуйте снова.", null, "Закрыть", null);
                error.Show();
                btnLogin.Enabled = true;
            }
            else
            {
                var record = new SecRecord(SecKind.GenericPassword)
                {
                    Description = KeyChain.Description,
                    Comment     = KeyChain.Comment,
                    Service     = KeyChain.Service,
                    Label       = KeyChain.Label,
                    Account     = txtLogin.Text,
                    ValueData   = NSData.FromString(txtPassword.Text),
                    Generic     = NSData.FromString(KeyChain.Generic),
                    Accessible  = SecAccessible.Always
                };
                SecStatusCode code = SecKeyChain.Add(record);
                if (code == SecStatusCode.DuplicateItem)
                {
                    code = SecKeyChain.Remove(existingRec);
                }
                if (code == SecStatusCode.Success)
                {
                    code = SecKeyChain.Add(record);
                }


                PerformSegue("autherication", this);
            }
        }
        public void SetKey(string keyName, string keyValue)
        {
            var statusCode = SecStatusCode.Success;

            //
            // Remove any existing record
            ///
            var existing = GetKey(keyName);

            if (!string.IsNullOrEmpty(existing))
            {
                DeleteKey(keyName);
            }

            //
            // Add this record
            //
            var data   = NSData.FromString(keyValue);
            var record = new SecRecord(SecKind.GenericPassword);

            record.Service    = serviceId;
            record.Account    = keyName;
            record.Generic    = data;
            record.Accessible = SecAccessible.WhenUnlocked;

            statusCode = SecKeyChain.Add(record);

            if (statusCode != SecStatusCode.Success)
            {
                throw new Exception("Could not save key to KeyChain: " + statusCode);
            }
        }
Ejemplo n.º 13
0
        public void InstallCertificate(string certificate)
        {
            if (certificate.StartsWith("http", StringComparison.CurrentCulture))
            {
                OpenUrlExternally(certificate);
            }

            //THIS CASE DOESN"T WORK YET, WE CAN ONLY ADD THE CERT TO THE KEYCHAIN BUT NOT PROMPT FOR TRUST
            else
            {
                NSData certData = NSData.FromUrl(new NSUrl(certificate));

                SecCertificate secCertificate = new SecCertificate(certData);

                SecRecord secRecord = new SecRecord(SecKind.Certificate);

                secRecord.SetValueRef(secCertificate);


                SecPolicy policy   = SecPolicy.CreateSslPolicy(true, "applocker.navy.mil");
                SecTrust  secTrust = new SecTrust(secCertificate, policy);
                //SecTrustResult results = secTrust.GetTrustResult();

                SecStatusCode code = SecKeyChain.Add(secRecord);
                Console.WriteLine(code);
            }
        }
Ejemplo n.º 14
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);
            }
        }
        internal SecStatusCode SaveBrokerApplicationToken(string clientIdAsKey, string applicationToken)
        {
            // The broker application token is used starting w/iOS broker 6.3.19+ (v3)
            // If the application cannot be verified, an additional user consent dialog will be required the first time
            // when the application is using the iOS broker.
            // After initial user consent, the iOS broker will issue a token to the application that will
            // grant application access to its own cache on subsequent broker invocations.
            // On subsequent calls, the application presents the application token to the iOS broker, this will prevent
            // the showing of the consent dialog.
            var recordToSave = new SecRecord(SecKind.GenericPassword)
            {
                Account        = clientIdAsKey,
                Service        = iOSBrokerConstants.iOSBroker,
                ValueData      = NSData.FromString(applicationToken, NSStringEncoding.UTF8),
                AccessGroup    = _keychainGroup,
                Accessible     = _defaultAccessiblityPolicy,
                Synchronizable = _defaultSyncSetting
            };

            SecStatusCode secStatusCode = Update(recordToSave);

            if (secStatusCode == SecStatusCode.ItemNotFound)
            {
                secStatusCode = SecKeyChain.Add(recordToSave);
            }

            return(secStatusCode);
        }
Ejemplo n.º 16
0
        public void Add_Certificate()
        {
#if MONOMAC && !NET
            Stream certStream = typeof(KeyChainTest).Assembly.GetManifestResourceStream("xammac_tests.Security.openssl_crt.der");
#else
            Stream certStream = typeof(KeyChainTest).Assembly.GetManifestResourceStream("monotouchtest.Security.openssl_crt.der");
#endif
            NSData data = NSData.FromStream(certStream);

            var query = new SecRecord(SecKind.Certificate)
            {
                Label = $"Internet Widgits Pty Ltd",
            };
            var rec = query.Clone();
            rec.SetValueRef(new SecCertificate(data));

            try {
                // delete any existing certificates first.
                SecKeyChain.Remove(query);
                // add the new certificate
                var rc = SecKeyChain.Add(rec);
                Assert.That(rc, Is.EqualTo(SecStatusCode.Success), "Add_Certificate");
            } finally {
                // clean up after ourselves
                SecKeyChain.Remove(query);
            }
        }
        private string GetTeamId()
        {
            var queryRecord = new SecRecord(SecKind.GenericPassword)
            {
                Service    = "",
                Account    = TeamIdKey,
                Accessible = SecAccessible.Always
            };

            SecRecord match = SecKeyChain.QueryAsRecord(queryRecord, out SecStatusCode resultCode);

            if (resultCode == SecStatusCode.ItemNotFound)
            {
                SecKeyChain.Add(queryRecord);
                match = SecKeyChain.QueryAsRecord(queryRecord, out resultCode);
            }

            if (resultCode == SecStatusCode.Success)
            {
                return(match.AccessGroup.Split('.')[0]);
            }

            throw new MsalClientException(
                      MsalError.CannotAccessPublisherKeyChain,
                      MsalErrorMessage.CannotAccessPublisherKeyChain);
        }
        public void AfterAccess(TokenCacheNotificationArgs args)
        {
            if (args.TokenCache.HasStateChanged)
            {
                try
                {
                    var s = new SecRecord(SecKind.GenericPassword)
                    {
                        Generic     = NSData.FromString(LocalSettingsContainerName),
                        Accessible  = SecAccessible.Always,
                        Service     = "ADAL.PCL.iOS Service",
                        Account     = "ADAL.PCL.iOS cache",
                        Label       = "ADAL.PCL.iOS Label",
                        Comment     = "ADAL.PCL.iOS Cache",
                        Description = "Storage for cache"
                    };

                    var err = SecKeyChain.Remove(s);
                    if (args.TokenCache.Count > 0)
                    {
                        s.ValueData = NSData.FromArray(args.TokenCache.Serialize());
                        err         = SecKeyChain.Add(s);
                    }

                    args.TokenCache.HasStateChanged = false;
                }
                catch (Exception ex)
                {
                    PlatformPlugin.Logger.Warning(null, "Failed to save cache: " + ex);
                }
            }
        }
Ejemplo n.º 19
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());
            }
        }
Ejemplo n.º 20
0
        public async Task SaveAsync <T>(string key, T obj)
        {
            if (obj == null)
            {
                await RemoveAsync(key);

                return;
            }

            string dataString = null;

            if (typeof(T) == typeof(string))
            {
                dataString = obj as string;
            }
            else
            {
                dataString = JsonConvert.SerializeObject(obj, _jsonSettings);
            }

            var appId = await _getAppId.Invoke();

            var formattedKey = string.Format(_keyFormat, appId, key);
            var dataBytes    = Encoding.UTF8.GetBytes(dataString);

            using (var data = NSData.FromArray(dataBytes))
                using (var newRecord = GetKeyRecord(formattedKey, data))
                {
                    await RemoveAsync(key);

                    CheckError(SecKeyChain.Add(newRecord));
                }
        }
        public void SaveCredentials(string userName, string password)
        {
            var s = new SecRecord(SecKind.GenericPassword)
            {
                Label       = "Item Label",
                Description = "Item description",
                Account     = Constants.ApplicationName,
                Service     = "CardinalPassword",
                Comment     = "CardinalUsernamePassword",
                ValueData   = NSData.FromString(password),
                Generic     = NSData.FromString("foo")
            };

            var err = SecKeyChain.Add(s);

            //if (err != SecStatusCode.Success && err != SecStatusCode.DuplicateItem)
            //    DisplayMessage(this, "Error adding record: {0}", err);


            //var record = new SecRecord(SecKind.GenericPassword)
            //{
            //    Service = Constants.ApplicationName,
            //    Account = userName,
            //    ValueData = NSData.FromString(userName, NSStringEncoding.UTF8),
            //    Accessible = SecAccessible.WhenUnlocked,
            //    Generic = NSData.FromString(userName, NSStringEncoding.UTF8)
            //};

            //var statusCode = SecKeyChain.Add(record);
            //if(statusCode.Equals())
        }
        public void SaveUserInfo(string userId, string userName, string password)
        {
            var rec = new SecRecord(SecKind.GenericPassword)
            {
                Generic = NSData.FromString("password")
            };

            SecStatusCode res;
            var           match = SecKeyChain.QueryAsRecord(rec, out res);

            if (res == SecStatusCode.Success)
            {
                res = SecKeyChain.Remove(rec);
            }

            var s = new SecRecord(SecKind.GenericPassword)
            {
                Service   = "BodyReportUserInfo",
                Account   = userId + (char)3 + userName,
                ValueData = NSData.FromString(password),
                Generic   = NSData.FromString("password")
            };

            res = SecKeyChain.Add(s);
        }
Ejemplo n.º 23
0
        public void SetSecured(string key, string value, string clientId, string service, string sharedGroupId)
        {
            var s = new SecRecord(SecKind.GenericPassword)
            {
                Service = $"{clientId}-{key}-{service}",
            };

            SecStatusCode res;
            var           match = SecKeyChain.QueryAsRecord(s, out res);

            if (res == SecStatusCode.Success)
            {
                var remStatus = SecKeyChain.Remove(s);
            }

            s.ValueData = NSData.FromString(value);

            if (!string.IsNullOrWhiteSpace(sharedGroupId))
            {
                s.AccessGroup = sharedGroupId;
            }

            var err = SecKeyChain.Add(s);

            Console.WriteLine(err);
        }
            public void SetValueForKey(string value, string key)
            {
                var record = ExistingRecordForKey(key);

                if (string.IsNullOrEmpty(value))
                {
                    if (!string.IsNullOrEmpty(ValueForKey(key)))
                    {
                        RemoveRecord(record);
                    }

                    return;
                }

                // if the key already exists, remove it
                if (!string.IsNullOrEmpty(ValueForKey(key)))
                {
                    RemoveRecord(record);
                }

                var result = SecKeyChain.Add(CreateRecordForNewKeyValue(key, value));

                if (result != SecStatusCode.Success)
                {
                    throw new Exception(String.Format("Error adding record: {0}", result));
                }
            }
Ejemplo n.º 25
0
        void Protocol(SecProtocol protocol)
        {
            var rec = new SecRecord(SecKind.InternetPassword)
            {
                Account = "Protocol"
            };

            SecKeyChain.Remove(rec);              // it might already exists (or not)

            rec = new SecRecord(SecKind.InternetPassword)
            {
                Account   = "Protocol",
                ValueData = NSData.FromString("Password"),
                Protocol  = protocol,
                Server    = "www.xamarin.com"
            };

            Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add");

            SecStatusCode code;
            var           match = SecKeyChain.QueryAsRecord(rec, out code);

            Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord");

            Assert.That(match.Protocol, Is.EqualTo(protocol), "Protocol");
        }
        public override Task <bool> AddSecureDataAsync(string key, string value)
        {
            var secObject = new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.TouchIDCurrentSet);

            if (secObject == null)
            {
                //todo:handle error
            }

            var securityRecord = new SecRecord(SecKind.Key)
            {
                Service       = key,
                ValueData     = new NSString(value).Encode(NSStringEncoding.UTF8),
                AccessControl = secObject
            };

            TaskCompletionSource <bool> response = new TaskCompletionSource <bool>();

            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                SecStatusCode status = SecKeyChain.Add(securityRecord);
                if (status == SecStatusCode.Success)
                {
                    response.TrySetResult(true);
                }
                else
                {
                    throw new Exception(status.ToString());
                }
            });
            return(response.Task);
        }
Ejemplo n.º 27
0
        public static bool SaveUserPassword(string username, string password)
        {
            var success      = false;
            var searchRecord = new SecRecord(SecKind.InternetPassword)
            {
                Server  = "Test1",
                Account = username.ToLower()
            };
            SecStatusCode queryCode;
            var           record = SecKeyChain.QueryAsRecord(searchRecord, out queryCode);

            if (queryCode == SecStatusCode.ItemNotFound)
            {
                record = new SecRecord(SecKind.InternetPassword)
                {
                    Server    = "Test1",
                    Account   = username.ToLower(),
                    ValueData = NSData.FromString(password)
                };
                var addCode = SecKeyChain.Add(record);
                success = (addCode == SecStatusCode.Success);
            }
            if (queryCode == SecStatusCode.Success && record != null)
            {
                record.ValueData = NSData.FromString(password);
                var updateCode = SecKeyChain.Update(searchRecord, record);
                success = (updateCode == SecStatusCode.Success);
            }
            return(success);
        }
        private SecStatusCode Save(IiOSKey key, string payload)
        {
            var recordToSave = new SecRecord(SecKind.GenericPassword)
            {
                Account        = key.iOSAccount,
                Service        = key.iOSService,
                Generic        = key.iOSGeneric,
                CreatorType    = key.iOSType,
                ValueData      = NSData.FromString(payload, NSStringEncoding.UTF8),
                AccessGroup    = _keychainGroup,
                Accessible     = _defaultAccessiblityPolicy,
                Synchronizable = _defaultSyncSetting,
            };

            var secStatusCode = Update(recordToSave);

            if (secStatusCode == SecStatusCode.ItemNotFound)
            {
                secStatusCode = SecKeyChain.Add(recordToSave);
            }

            if (secStatusCode == SecStatusCode.MissingEntitlement)
            {
                throw new MsalClientException(
                          MsalError.MissingEntitlements,
                          string.Format(
                              CultureInfo.InvariantCulture,
                              MsalErrorMessage.MissingEntitlements,
                              recordToSave.AccessGroup));
            }

            return(secStatusCode);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Sets a password for a specific username.
        /// </summary>
        /// <param name="sUsername">the username to add the password for. May not be NULL.</param>
        /// <param name="sPassword">the password to associate with the record. May not be NULL.</param>
        /// <param name="sService">the service description to use. May not be NULL.</param>
        /// <param name="eSecAccessible">defines how the keychain record is protected</param>
        /// <returns>SecStatusCode.Success if everything went fine, otherwise some other status</returns>
        //------------------------------------------------------------------------------
        public static SecStatusCode SetPasswordForUsername(string sUsername, string sPassword, string sService, SecAccessible eSecAccessible, bool bSynchronizable)
        {
            if (sUsername == null)
            {
                throw new ArgumentNullException(nameof(sUsername));
            }

            if (sService == null)
            {
                throw new ArgumentNullException(nameof(sService));
            }

            if (sPassword == null)
            {
                throw new ArgumentNullException(nameof(sPassword));
            }

            // Don't bother updating. Delete existing record and create a new one.
            DeletePasswordForUsername(sUsername, sService, bSynchronizable);

            // Create a new record.
            // Store password UTF8 encoded.
            SecStatusCode eCode = SecKeyChain.Add(new SecRecord(SecKind.GenericPassword)
            {
                Service        = sService,
                Label          = sService,
                Account        = sUsername,
                Generic        = NSData.FromString(sPassword, NSStringEncoding.UTF8),
                Accessible     = eSecAccessible,
                Synchronizable = bSynchronizable
            });

            return(eCode);
        }
Ejemplo n.º 30
0
        void Protocol(SecProtocol protocol)
        {
            var rec = new SecRecord(SecKind.InternetPassword)
            {
                Account = $"Protocol-{protocol}-{CFBundle.GetMain ().Identifier}-{GetType ().FullName}-{Process.GetCurrentProcess ().Id}",
            };

            try {
                SecKeyChain.Remove(rec);                  // it might already exists (or not)

                rec = new SecRecord(SecKind.InternetPassword)
                {
                    Account   = "Protocol",
                    ValueData = NSData.FromString("Password"),
                    Protocol  = protocol,
                    Server    = "www.xamarin.com"
                };

                Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add");

                SecStatusCode code;
                var           match = SecKeyChain.QueryAsRecord(rec, out code);
                Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord");

                Assert.That(match.Protocol, Is.EqualTo(protocol), "Protocol");
            } finally {
                // Clean up after us
                SecKeyChain.Remove(rec);
            }
        }