public void TestEquals() { GuardedString str1 = new GuardedString(); GuardedString str2 = new GuardedString(); Assert.AreEqual(str1, str2); str2.AppendChar('2'); Assert.AreNotEqual(str1, str2); str1.AppendChar('2'); Assert.AreEqual(str1, str2); }
public void TestBasics() { GuardedString ss = new GuardedString(); ss.AppendChar('f'); ss.AppendChar('o'); ss.AppendChar('o'); ss.AppendChar('b'); ss.AppendChar('a'); ss.AppendChar('r'); String decrypted = DecryptToString(ss); Assert.AreEqual("foobar", decrypted); String hash = ss.GetBase64SHA1Hash(); Assert.IsTrue(ss.VerifyBase64SHA1Hash(hash)); ss.AppendChar('2'); Assert.IsFalse(ss.VerifyBase64SHA1Hash(hash)); }
public void TestUnicode() { for (int i = 0; i < 0xFFFF; i++) { int expected = i; char c = (char)i; GuardedString gs = new GuardedString(); gs = (GuardedString)SerializerUtil.CloneObject(gs); gs.AppendChar(c); gs.Access(new GuardedString.LambdaAccessor(clearChars => { int v = (int)clearChars[0]; Assert.AreEqual(expected, v); })); } }
private static void DoStoreCertificate(IDictionary <string, string> options) { string storeName = options.ContainsKey(OPT_CERTSTOR_NAME) ? options[OPT_CERTSTOR_NAME] : "ConnectorServerSSLCertificate"; if (!options.ContainsKey(OPT_CERTFILE_NAME) || String.IsNullOrEmpty(options[OPT_CERTFILE_NAME])) { Usage(); throw new Org.IdentityConnectors.Framework.Common.Exceptions.ConfigurationException("Missing required argument: " + OPT_CERTFILE_NAME); } X509Certificate2 certificate = null; try { certificate = new X509Certificate2(options[OPT_CERTFILE_NAME]); } catch (CryptographicException) { Console.Write("Please enter the keystore password: "******"Previous certificate has been removed."); } else { Console.WriteLine("There are multiple certificates were found. You may point to the wrong store."); throw new Org.IdentityConnectors.Framework.Common.Exceptions.ConfigurationException("There is supported to be exactly one certificate in the store: " + storeName); } } store.Add(certificate); store.Close(); Console.WriteLine("Certificate is stored in " + storeName); }
private static GuardedString ReadPassword() { GuardedString rv = new GuardedString(); while (true) { ConsoleKeyInfo info = Console.ReadKey(true); if (info.Key == ConsoleKey.Enter) { Console.WriteLine(); rv.MakeReadOnly(); return(rv); } else { Console.Write("*"); rv.AppendChar(info.KeyChar); } } }
/// <summary> /// Creates a new instance of RemoteFrameworkConnectionInfo. /// </summary> /// <param name="host">The host to connect to</param> /// <param name="port">The port to connect to</param> /// <param name="useSSL">Set to true if we are to connect via SSL.</param> /// <param name="certificateValidationCallback">to use /// for establising the SSL connection. May be null or empty, /// in which case the default installed providers for the JVM will /// be used. Ignored if 'useSSL' is false.</param> /// <param name="timeout">The timeout to use (in milliseconds). A value of 0 /// means infinite timeout;</param> public RemoteFrameworkConnectionInfo(String host, int port, GuardedString key, bool useSSL, RemoteCertificateValidationCallback certificateValidationCallback, int timeout) { if (host == null) { throw new ArgumentException("Parameter 'host' is null."); } if (key == null) { throw new ArgumentException("Parameter 'key' is null."); } _host = host; _port = port; _key = key; _useSSL = useSSL; _certificateValidationCallback = certificateValidationCallback; _timeout = timeout; }
protected override ConnectorInfoManager GetConnectorInfoManager() { TestUtil.InitializeLogging(); GuardedString str = new GuardedString(); str.AppendChar('c'); str.AppendChar('h'); str.AppendChar('a'); str.AppendChar('n'); str.AppendChar('g'); str.AppendChar('e'); str.AppendChar('i'); str.AppendChar('t'); #if DEBUG const int PORT = 58758; #else const int PORT = 58759; #endif _server = ConnectorServer.NewInstance(); _server.Port = PORT; _server.IfAddress = (IOUtil.GetIPAddress("127.0.0.1")); _server.KeyHash = str.GetBase64SHA1Hash(); _server.Start(); //while ( true ) { // Thread.Sleep(1000); //} ConnectorInfoManagerFactory fact = ConnectorInfoManagerFactory.GetInstance(); RemoteFrameworkConnectionInfo connInfo = new RemoteFrameworkConnectionInfo("127.0.0.1", PORT, str); ConnectorInfoManager manager = fact.GetRemoteManager(connInfo); return(manager); }
public MsPowerShellConfiguration() { AuthenticateScriptFileName = ""; CreateScriptFileName = ""; DeleteScriptFileName = ""; ResolveUsernameScriptFileName = ""; SchemaScriptFileName = ""; SearchScriptFileName = ""; SyncScriptFileName = ""; TestScriptFileName = ""; UpdateScriptFileName = ""; VariablesPrefix = "Connector"; QueryFilterType = MsPowerShellConnector.Visitors.Map.ToString(); SubstituteUidAndNameInQueryFilter = false; ReloadScriptOnExecution = false; UseInterpretersPool = true; UidAttributeName = Uid.NAME; NameAttributeName = Name.NAME; PsModulesToImport = new string[] {}; Host = ""; Port = null; Login = ""; Password = null; }
/// <summary> /// Builds the operational attribute password. /// </summary> /// <param name="password">the string that represents a password.</param> /// <returns>an attribute that represents a password.</returns> public static ConnectorAttribute BuildPassword(GuardedString password) { return Build(OperationalAttributes.PASSWORD_NAME, password); }
public static bool Verify(String principalKey, String password) { GuardedString key = new GuardedString(); password.ToCharArray().ToList().ForEach(p => key.AppendChar(p)); try { return key.VerifyBase64SHA1Hash(principalKey); } finally { key.Dispose(); } }
public GuardedString GetGuardedString(string regularString) { GuardedString guardedString = new GuardedString(); foreach (char c in regularString) { guardedString.AppendChar(c); } return guardedString; }
public void TestCreateTestConfiguration() { IDictionary <string, object> expectedData = new Dictionary <string, object>(); expectedData["String"] = "retipipiter"; expectedData["StringArray"] = new [] { "value1", "value2", "value3" }; expectedData["Long"] = 11L; expectedData["LongArray"] = new [] { 12L, 13L }; expectedData["LongObject"] = 14L; expectedData["LongObjectArray"] = new long?[] { 15, null }; expectedData["Char"] = 'a'; expectedData["CharArray"] = new [] { 'b', 'c' }; expectedData["Character"] = 'd'; expectedData["CharacterArray"] = new char?[] { 'e', 'f' }; expectedData["Double"] = 0D; expectedData["DoubleArray"] = new [] { 0D, 100D }; expectedData["DoubleObject"] = 0d; expectedData["DoubleObjectArray"] = new double?[] { 0D, 100D }; expectedData["Float"] = 0F; expectedData["FloatArray"] = new[] { 0F, 100F }; expectedData["FloatObject"] = null; expectedData["FloatObjectArray"] = new float?[] { 0F, 100F }; expectedData["Int"] = 0; expectedData["IntArray"] = new[] { 0, 100 }; expectedData["Integer"] = 0; expectedData["IntegerArray"] = new int?[] { 0, 100 }; expectedData["Boolean"] = true; expectedData["BooleanArray"] = new[] { true, false }; expectedData["BooleanObject"] = false; expectedData["BooleanObjectArray"] = new bool?[] { true, false }; expectedData["URI"] = new Uri("http://localhost:8080"); expectedData["URIArray"] = ""; expectedData["URIArray"] = new[] { new Uri("http://localhost:8080"), new Uri("http://localhost:8443") }; expectedData["File"] = new FileName("c:\\Users\\Admin"); expectedData["FileArray"] = new[] { new FileName("c:\\Users\\Admin\\Documents"), new FileName("c:\\Users\\Admin\\Settings") }; var array = new GuardedByteArray(); Encoding.UTF8.GetBytes("array").ToList().ForEach(array.AppendByte); expectedData["GuardedByteArray"] = array; array = new GuardedByteArray(); Encoding.UTF8.GetBytes("item1").ToList().ForEach(array.AppendByte); var array2 = new GuardedByteArray(); Encoding.UTF8.GetBytes("item2").ToList().ForEach(array2.AppendByte); expectedData["GuardedByteArrayArray"] = new [] { array, array2 }; var secret = new GuardedString(); "secret".ToCharArray().ToList().ForEach(secret.AppendChar); expectedData["GuardedString"] = secret; secret = new GuardedString(); "secret1".ToCharArray().ToList().ForEach(secret.AppendChar); var secret2 = new GuardedString(); "secret2".ToCharArray().ToList().ForEach(secret2.AppendChar); expectedData["GuardedStringArray"] = new[] { secret, secret2 }; expectedData["Script"] = new ScriptBuilder { ScriptLanguage = "PowerShell", ScriptText = "echo 'Hello OpenICF Developer'" }.Build(); expectedData["ScriptArray"] = new[] { new ScriptBuilder { ScriptLanguage = "Groovy", ScriptText = "println 'Hello'" }.Build(), new ScriptBuilder { ScriptLanguage = "Groovy", ScriptText = "println 'OpenICF Developer'" }.Build() }; Environment.SetEnvironmentVariable(TestHelpers.TestConfigEVName, "converter"); FieldInfo info = typeof(TestHelpers).GetField("_propertyBags", BindingFlags.NonPublic | BindingFlags.Static); (info.GetValue(null) as Dictionary <string, PropertyBag>).Clear(); PropertyBag propertyBag = TestHelpers.GetProperties(typeof(Org.IdentityConnectors.TestConnector.FakeConnector)); (info.GetValue(null) as Dictionary <string, PropertyBag>).Clear(); APIConfiguration testable = TestHelpers.CreateTestConfiguration(SafeType <Connector> .Get <Org.IdentityConnectors.TestConnector.FakeConnector>(), propertyBag, null); foreach (KeyValuePair <string, object> entry in expectedData) { Assert.AreEqual(entry.Value, testable.ConfigurationProperties.GetProperty(entry.Key).Value, "Configuration property: " + entry.Key + " has different value"); } }
protected override ConnectorInfoManager GetConnectorInfoManager() { TestUtil.InitializeLogging(); GuardedString str = new GuardedString(); str.AppendChar('c'); str.AppendChar('h'); str.AppendChar('a'); str.AppendChar('n'); str.AppendChar('g'); str.AppendChar('e'); str.AppendChar('i'); str.AppendChar('t'); #if DEBUG const int PORT = 58758; #else const int PORT = 58759; #endif _server = ConnectorServer.NewInstance(); _server.Port = PORT; _server.IfAddress = (IOUtil.GetIPAddress("127.0.0.1")); _server.KeyHash = str.GetBase64SHA1Hash(); _server.Start(); //while ( true ) { // Thread.Sleep(1000); //} ConnectorInfoManagerFactory fact = ConnectorInfoManagerFactory.GetInstance(); RemoteFrameworkConnectionInfo connInfo = new RemoteFrameworkConnectionInfo("127.0.0.1", PORT, str); ConnectorInfoManager manager = fact.GetRemoteManager(connInfo); return manager; }
public void TestGuardedString() { GuardedString v1 = new GuardedString(); v1.AppendChar('f'); v1.AppendChar('o'); v1.AppendChar('o'); v1.AppendChar('b'); v1.AppendChar('a'); v1.AppendChar('r'); GuardedString v2 = (GuardedString)CloneObject(v1); Assert.AreEqual("foobar", DecryptToString(v2)); }
public ICollection<ConnectorAttribute> GetAllAttributes_Account() { ICollection<ConnectorAttribute> attributes = new HashSet<ConnectorAttribute>(); int randomNumber = GetRandomNumber(); // the container ... is a fabricated attribute attributes.Add(ConnectorAttributeBuilder.Build( "ad_container", GetProperty(ConfigHelper.CONFIG_PROPERTY_CONTAINER))); GuardedString password = new GuardedString(); foreach (char c in "secret") { password.AppendChar(c); } attributes.Add(ConnectorAttributeBuilder.BuildPassword( password)); attributes.Add(ConnectorAttributeBuilder.Build( "sAMAccountName", "nunit" + randomNumber)); attributes.Add(ConnectorAttributeBuilder.Build( "givenName", "nunit")); attributes.Add(ConnectorAttributeBuilder.Build( "sn", "TestUser" + randomNumber)); attributes.Add(ConnectorAttributeBuilder.Build( "displayName", "nunit test user " + randomNumber)); attributes.Add(ConnectorAttributeBuilder.Build( "mail", "nunitUser" + randomNumber + "@some.com")); attributes.Add(ConnectorAttributeBuilder.Build( "telephoneNumber", "333-547-8453")); // attributes.Add(ConnectorAttributeBuilder.Build( // "msExchHomeServerName", "")); attributes.Add(ConnectorAttributeBuilder.Build( "employeeID", "1234567")); attributes.Add(ConnectorAttributeBuilder.Build( "division", "Identity Services")); attributes.Add(ConnectorAttributeBuilder.Build( "mobile", "554-210-8631")); // attributes.Add(ConnectorAttributeBuilder.Build( // "mDBOverQuotaLimit", "")); attributes.Add(ConnectorAttributeBuilder.Build( "middleName", "testCase")); attributes.Add(ConnectorAttributeBuilder.Build( "description", "This user was created as a test case for the AD Connector")); // attributes.Add(ConnectorAttributeBuilder.Build( // "mDBOverHardQuotaLimit", "")); // attributes.Add(ConnectorAttributeBuilder.Build( // "mDBUseDefaults", "")); attributes.Add(ConnectorAttributeBuilder.Build( "department", "Connector Affairs")); // for manager, it looks like the manager has to exist // attributes.Add(ConnectorAttributeBuilder.Build( // "manager", "Some Guy")); // attributes.Add(ConnectorAttributeBuilder.Build( // "mDBStorageQuota", "")); // attributes.Add(ConnectorAttributeBuilder.Build( // "mailNickName", "")); attributes.Add(ConnectorAttributeBuilder.Build( "title", "Manager")); attributes.Add(ConnectorAttributeBuilder.Build( "initials", "XYZ")); // attributes.Add(ConnectorAttributeBuilder.Build( // "homeMTA", "")); attributes.Add(ConnectorAttributeBuilder.Build( "co", "United States")); // attributes.Add(ConnectorAttributeBuilder.Build( // "homeMDB", "")); attributes.Add(ConnectorAttributeBuilder.Build( "company", "NUnit Test Company")); attributes.Add(ConnectorAttributeBuilder.Build( "facsimileTelephoneNumber", "111-222-3333")); attributes.Add(ConnectorAttributeBuilder.Build( "homePhone", "222-333-4444")); // attributes.Add(ConnectorAttributeBuilder.Build( // "directoryEntryWS_PasswordExpired", "")); attributes.Add(ConnectorAttributeBuilder.Build( "streetAddress", "12345 Some Street")); attributes.Add(ConnectorAttributeBuilder.Build( "l", "Austin")); attributes.Add(ConnectorAttributeBuilder.Build( "st", "Texas")); attributes.Add(ConnectorAttributeBuilder.Build( "postalCode", "78717")); // attributes.Add(ConnectorAttributeBuilder.Build( // "AccountLocked", "")); // used to be 'Terminal Services Initial Program' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_INITIAL_PROGRAM, "myprog.exe")); // used to be 'Terminal Services Initial Program Directory' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_INITIAL_PROGRAM_DIR, "c:\\nunittest\\dir")); // unknown ... // attributes.Add(ConnectorAttributeBuilder.Build( // "Terminal Services Inherit Initial Program", true)); // used to be 'Terminal Services Allow Logon' - defaults to false, so testing true attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_ALLOW_LOGON, 1)); // used to be 'Terminal Services Active Session Timeout' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_MAX_CONNECTION_TIME, 10000)); // used to be 'Terminal Services Disconnected Session Timeout' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_MAX_DISCONNECTION_TIME, 20000)); // used to be 'Terminal Services Idle Timeout' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_MAX_IDLE_TIME, 30000)); // used to be 'Terminal Services Connect Client Drives At Logon' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_CONNECT_CLIENT_DRIVES_AT_LOGON, 1)); // used to be 'Terminal Services Connect Client Printers At Logon' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_CONNECT_CLIENT_PRINTERS_AT_LOGON, 1)); // used to be 'Terminal Services Default To Main Client Printer' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_DEFAULT_TO_MAIN_PRINTER, 1)); // used to be 'Terminal Services End Session On Timeout Or Broken Connection' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_BROKEN_CONNECTION_ACTION, 1)); // used to be 'Terminal Services Allow Reconnect From Originating Client Only' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_RECONNECTION_ACTION, 1)); // attributes.Add(ConnectorAttributeBuilder.Build( // "Terminal Services Callback Settings", "")); // attributes.Add(ConnectorAttributeBuilder.Build( // "Terminal Services Callback Phone Number", "")); // used to be 'Terminal Services Remote Control Settings' attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_ENABLE_REMOTE_CONTROL, 1)); // used to be 'Terminal Services User Profile attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_PROFILE_PATH, "\\My Profile")); // used to be 'Terminal Services Local Home Directory attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_HOME_DIRECTORY, "\\My Home Dir")); // used to be 'Terminal Services Home Directory Drive attributes.Add(ConnectorAttributeBuilder.Build( TerminalServicesUtils.TS_HOME_DRIVE, "C:")); // uSNChanged should be read only // attributes.Add(ConnectorAttributeBuilder.Build( // "uSNChanged", "")); // objectGUID should be read only // attributes.Add(ConnectorAttributeBuilder.Build( // "objectGUID", "")); // now set name operational attribute attributes.Add(ConnectorAttributeBuilder.Build( Name.NAME, "cn=nunit" + randomNumber + "," + GetProperty(ConfigHelper.CONFIG_PROPERTY_CONTAINER))); /* // a few attributes not used in IDM // country code is not returned by default attributes.Add(ConnectorAttributeBuilder.Build( "countryCode", 23)); */ return attributes; }
/// <summary> /// Highly insecure method! Do not do this in production /// code. /// </summary> /// <remarks> /// This is only for test purposes /// </remarks> private String DecryptToString(GuardedString str) { StringBuilder buf = new StringBuilder(); str.Access(new GuardedString.LambdaAccessor( array => { for (int i = 0; i < array.Length; i++) { buf.Append(array[i]); } })); return buf.ToString(); }
public void TestCreateTestConfiguration() { IDictionary<string, object> expectedData = new Dictionary<string, object>(); expectedData["String"] = "retipipiter"; expectedData["StringArray"] = new [] { "value1", "value2", "value3" }; expectedData["Long"] = 11L; expectedData["LongArray"] = new []{12L, 13L}; expectedData["LongObject"] = 14L; expectedData["LongObjectArray"] = new long?[]{15, null}; expectedData["Char"] = 'a'; expectedData["CharArray"] = new []{'b','c'}; expectedData["Character"] = 'd'; expectedData["CharacterArray"] = new char?[]{'e','f'}; expectedData["Double"] = 0D; expectedData["DoubleArray"] = new []{0D, 100D}; expectedData["DoubleObject"] = 0d; expectedData["DoubleObjectArray"] = new double?[] { 0D, 100D }; expectedData["Float"] = 0F; expectedData["FloatArray"] = new[] { 0F, 100F }; expectedData["FloatObject"] = null; expectedData["FloatObjectArray"] = new float?[] { 0F, 100F }; expectedData["Int"] = 0; expectedData["IntArray"] = new[] { 0, 100 }; expectedData["Integer"] = 0; expectedData["IntegerArray"] = new int?[] { 0, 100 }; expectedData["Boolean"] = true; expectedData["BooleanArray"] = new[]{true, false}; expectedData["BooleanObject"] = false; expectedData["BooleanObjectArray"] = new bool?[] { true, false }; expectedData["URI"] = new Uri("http://localhost:8080"); expectedData["URIArray"] = ""; expectedData["URIArray"] = new[] { new Uri("http://localhost:8080"), new Uri("http://localhost:8443") }; expectedData["File"] = new FileName("c:\\Users\\Admin"); expectedData["FileArray"] = new[] {new FileName("c:\\Users\\Admin\\Documents"), new FileName("c:\\Users\\Admin\\Settings")}; var array = new GuardedByteArray(); Encoding.UTF8.GetBytes("array").ToList().ForEach(array.AppendByte); expectedData["GuardedByteArray"] = array; array = new GuardedByteArray(); Encoding.UTF8.GetBytes("item1").ToList().ForEach(array.AppendByte); var array2 = new GuardedByteArray(); Encoding.UTF8.GetBytes("item2").ToList().ForEach(array2.AppendByte); expectedData["GuardedByteArrayArray"] = new []{array, array2}; var secret = new GuardedString(); "secret".ToCharArray().ToList().ForEach(secret.AppendChar); expectedData["GuardedString"] = secret; secret = new GuardedString(); "secret1".ToCharArray().ToList().ForEach(secret.AppendChar); var secret2 = new GuardedString(); "secret2".ToCharArray().ToList().ForEach(secret2.AppendChar); expectedData["GuardedStringArray"] = new[]{secret, secret2}; expectedData["Script"] = new ScriptBuilder { ScriptLanguage = "PowerShell", ScriptText = "echo 'Hello OpenICF Developer'" }.Build(); expectedData["ScriptArray"] = new[]{new ScriptBuilder { ScriptLanguage = "Groovy", ScriptText = "println 'Hello'" }.Build(),new ScriptBuilder { ScriptLanguage = "Groovy", ScriptText = "println 'OpenICF Developer'" }.Build()}; Environment.SetEnvironmentVariable(TestHelpers.TestConfigEVName, "converter"); FieldInfo info = typeof (TestHelpers).GetField("_propertyBags", BindingFlags.NonPublic | BindingFlags.Static); (info.GetValue(null) as Dictionary<string, PropertyBag>).Clear(); PropertyBag propertyBag = TestHelpers.GetProperties(typeof(Org.IdentityConnectors.TestConnector.FakeConnector)); (info.GetValue(null) as Dictionary<string, PropertyBag>).Clear(); APIConfiguration testable = TestHelpers.CreateTestConfiguration(SafeType<Connector>.Get<Org.IdentityConnectors.TestConnector.FakeConnector>(), propertyBag, null); foreach (KeyValuePair<string, object> entry in expectedData) { Assert.AreEqual(entry.Value, testable.ConfigurationProperties.GetProperty(entry.Key).Value, "Configuration property: " + entry.Key + " has different value"); } }
public void TestOperations() { IAsyncConnectorInfoManager manager = ConnectorInfoManager; var task = manager.FindConnectorInfoAsync(TestStatefulConnectorKey); Assert.IsTrue(task.Wait(TimeSpan.FromMinutes(5))); ConnectorFacade facade = ConnectorFacade; facade.Test(); Assert.IsNotNull(facade.Schema()); var guardedString = new GuardedString(); "Passw0rd".ToCharArray().ToList().ForEach(p => guardedString.AppendChar(p)); Uid uid1 = facade.Create(ObjectClass.ACCOUNT, CollectionUtil.NewSet(new Name("CREATE_01"), ConnectorAttributeBuilder.BuildPassword(guardedString)), null); Assert.IsNotNull(uid1); Uid uid2 = facade.Create(ObjectClass.ACCOUNT, CollectionUtil.NewSet(new Name("CREATE_02"), ConnectorAttributeBuilder.BuildPassword(guardedString)), null); Assert.AreNotEqual(uid1, uid2); Uid resolvedUid = facade.ResolveUsername(ObjectClass.ACCOUNT, "CREATE_01", null); Assert.AreEqual(uid1, resolvedUid); Uid authenticatedUid = facade.Authenticate(ObjectClass.ACCOUNT, "CREATE_01", guardedString, null); Assert.AreEqual(uid1, authenticatedUid); try { guardedString = new GuardedString(); "wrongPassw0rd".ToCharArray().ToList().ForEach(p => guardedString.AppendChar(p)); facade.Authenticate(ObjectClass.ACCOUNT, "CREATE_01", guardedString, null); Assert.Fail("This should fail"); } catch (Exception e) { Assert.AreEqual("Invalid Password", e.Message); } SyncToken token = facade.GetLatestSyncToken(ObjectClass.ACCOUNT); Assert.AreEqual(token.Value, 2); IList<SyncDelta> changes = new List<SyncDelta>(); Int32? index = null; SyncToken lastToken = facade.Sync(ObjectClass.ACCOUNT, new SyncToken(-1), new SyncResultsHandler { Handle = delta => { Int32? previous = index; index = (Int32?) delta.Token.Value; if (null != previous) { Assert.IsTrue(previous < index); } changes.Add(delta); return true; } }, null); Assert.AreEqual(changes.Count, 2); Assert.AreEqual(facade.GetObject(ObjectClass.ACCOUNT, uid1, null).Uid, uid1); Assert.AreEqual(token, lastToken); IList<ConnectorObject> connectorObjects = new List<ConnectorObject>(); facade.Search(ObjectClass.ACCOUNT, FilterBuilder.Or(FilterBuilder.EqualTo(new Name("CREATE_02")), FilterBuilder.StartsWith(new Name("CREATE"))), new ResultsHandler { Handle = connectorObject => { connectorObjects.Add(connectorObject); return true; } }, null); Assert.AreEqual(connectorObjects.Count, 2); connectorObjects = new List<ConnectorObject>(); facade.Search(ObjectClass.ACCOUNT, null, new ResultsHandler { Handle = connectorObject => { connectorObjects.Add(connectorObject); return true; } }, null); Assert.AreEqual(connectorObjects.Count, 2); Uid updatedUid = facade.Update(ObjectClass.ACCOUNT, uid1, CollectionUtil.NewSet(ConnectorAttributeBuilder.BuildLockOut(true)), null); ConnectorObject co = facade.GetObject(ObjectClass.ACCOUNT, updatedUid, null); var isLockedOut = ConnectorAttributeUtil.IsLockedOut(co); Assert.IsTrue(isLockedOut != null && (bool) isLockedOut); facade.Delete(ObjectClass.ACCOUNT, updatedUid, null); Assert.IsNull(facade.GetObject(ObjectClass.ACCOUNT, updatedUid, null)); }
/// <summary> /// Authenticates the user /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="returnUidOnly"></param> internal Uid Authenticate(/*DirectoryEntry directoryEntry,*/ string username, GuardedString password, bool returnUidOnly) { AuthenticationHelper authHelper = new AuthenticationHelper(_configuration); if(returnUidOnly) { return authHelper.GetUidFromSamAccountName(username); } _currentPassword = SecurityUtil.Decrypt(password); return authHelper.ValidateUserCredentials(username, _currentPassword); }
public void TestNullOperations() { IAsyncConnectorInfoManager manager = ConnectorInfoManager; var task = manager.FindConnectorInfoAsync(TestStatefulConnectorKey); Assert.IsTrue(task.Wait(TimeSpan.FromMinutes(5))); ConnectorFacade facade = GetConnectorFacade(true, true); OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder(); facade.Test(); Assert.IsNull(facade.Schema()); var guardedString = new GuardedString(); "Passw0rd".ToCharArray().ToList().ForEach(p => guardedString.AppendChar(p)); Uid uid = facade.Create(ObjectClass.ACCOUNT, CollectionUtil.NewSet(new Name("CREATE_01"), ConnectorAttributeBuilder.BuildPassword(guardedString)), optionsBuilder.Build()); Assert.IsNull(uid); Uid resolvedUid = facade.ResolveUsername(ObjectClass.ACCOUNT, "CREATE_01", optionsBuilder.Build()); Assert.IsNull(resolvedUid); Uid authenticatedUid = facade.Authenticate(ObjectClass.ACCOUNT, "CREATE_01", guardedString, optionsBuilder.Build()); Assert.IsNull(authenticatedUid); SyncToken token = facade.GetLatestSyncToken(ObjectClass.ACCOUNT); Assert.IsNull(token); SyncToken lastToken = facade.Sync(ObjectClass.ACCOUNT, new SyncToken(-1), new SyncResultsHandler {Handle = delta => true}, optionsBuilder.Build()); Assert.IsNull(lastToken); SearchResult searchResult = facade.Search(ObjectClass.ACCOUNT, null, new ResultsHandler {Handle = connectorObject => true}, optionsBuilder.Build()); Assert.IsNull(searchResult); Uid updatedUid = facade.Update(ObjectClass.ACCOUNT, new Uid("1"), CollectionUtil.NewSet(ConnectorAttributeBuilder.BuildLockOut(true)), optionsBuilder.Build()); Assert.IsNull(updatedUid); ConnectorObject co = facade.GetObject(ObjectClass.ACCOUNT, new Uid("1"), optionsBuilder.Build()); Assert.IsNull(co); ScriptContextBuilder contextBuilder = new ScriptContextBuilder { ScriptLanguage = "Boo", ScriptText = "arg" }; contextBuilder.AddScriptArgument("arg", "test"); object o = facade.RunScriptOnConnector(contextBuilder.Build(), optionsBuilder.Build()); Assert.AreEqual(o, "test"); o = facade.RunScriptOnResource(contextBuilder.Build(), optionsBuilder.Build()); Assert.IsNull(o); }
public void Init() { try { ConnectorFramework serverConnectorFramework = new ConnectorFramework(); ConnectorServerService.ConnectorServerService.InitializeConnectors(serverConnectorFramework.LocalManager); foreach (var connectorInfo in serverConnectorFramework.LocalManager.ConnectorInfos) { Trace.TraceInformation("Found Connector {0}", connectorInfo.ConnectorKey); } int freePort = FreePort; EndpointAddress serviceAddress = new EndpointAddress(String.Format("http://localhost:{0}/openicf", freePort)); var secureString = new GuardedString(); "changeit".ToCharArray().ToList().ForEach(p => secureString.AppendChar(p)); ClientAuthenticationValidator validator = new ClientAuthenticationValidator(); validator.Add(new SingleTenantPrincipal(serverConnectorFramework), secureString.GetBase64SHA1Hash()); _close = Start(validator, serviceAddress); _close += () => serverConnectorFramework.Dispose(); // ---------- _clientConnectorFramework = new ConnectorFramework(); _connectionInfo = new RemoteWSFrameworkConnectionInfo { RemoteUri = new Uri(String.Format("http://localhost.fiddler:{0}/openicf", freePort)), Principal = ConnectionPrincipal.DefaultName, Password = secureString }; } catch (Exception e) { TraceUtil.TraceException("Failed", e); throw; } }
protected override ConnectorInfoManager GetConnectorInfoManager() { TestUtil.InitializeLogging(); GuardedString str = new GuardedString(); str.AppendChar('c'); str.AppendChar('h'); str.AppendChar('a'); str.AppendChar('n'); str.AppendChar('g'); str.AppendChar('e'); str.AppendChar('i'); str.AppendChar('t'); #if DEBUG const int PORT = 58762; #else const int PORT = 58761; #endif /*X509Store store = new X509Store("TestCertificateStore", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly|OpenFlags.OpenExistingOnly); X509Certificate certificate = store.Certificates[0]; store.Close();*/ X509Certificate2 certificate = new X509Certificate2(CERT_PATH, "changeit"); //Trace.TraceInformation("certificate: "+certificate); _server = ConnectorServer.NewInstance(); _server.Port = PORT; _server.KeyHash = str.GetBase64SHA1Hash(); _server.IfAddress = (IOUtil.GetIPAddress("localhost")); _server.UseSSL = true; _server.ServerCertificate = certificate; _server.Start(); //while ( true ) { // Thread.Sleep(1000); //} ConnectorInfoManagerFactory fact = ConnectorInfoManagerFactory.GetInstance(); MyCertificateValidationCallback callback = new MyCertificateValidationCallback(); RemoteFrameworkConnectionInfo connInfo = new RemoteFrameworkConnectionInfo("localhost", PORT, str, true, callback.Validate, 60000); ConnectorInfoManager manager = fact.GetRemoteManager(connInfo); return manager; }
/// <summary> /// Creates a new instance of RemoteFrameworkConnectionInfo, using /// a clear (non-ssl) connection and a 60-second timeout. /// </summary> /// <param name="host">The host to connect to</param> /// <param name="port">The port to connect to</param> public RemoteFrameworkConnectionInfo(String host, int port, GuardedString key) : this(host, port, key, false, null, 60 * 1000) { }
private object ConvertFromString(string sourceValue, Type target) { if (typeof(string) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(long) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(long?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(long))); } } else if (typeof(char) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(char?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(char))); } } else if (typeof(double) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(double?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(double))); } } else if (typeof(float) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(float?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(float))); } } else if (typeof(int) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(int?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(int))); } } else if (typeof(bool) == target) { return(Convert.ChangeType(sourceValue, target)); } else if (typeof(bool?) == target) { if (StringUtil.IsBlank(sourceValue)) { return(null); } else { return(Convert.ChangeType(sourceValue, typeof(bool))); } } else if (typeof(Uri) == target) { return(new Uri(sourceValue)); } else if (typeof(FileName) == target) { return(new FileName(sourceValue)); } else if (typeof(GuardedByteArray) == target) { var result = new GuardedByteArray(); System.Text.Encoding.UTF8.GetBytes(sourceValue).ToList().ForEach(result.AppendByte); return(result); } else if (typeof(GuardedString) == target) { var result = new GuardedString(); sourceValue.ToCharArray().ToList().ForEach(result.AppendChar); return(result); } else if (typeof(Script) == target) { int i = sourceValue.IndexOf('|'); if (i > 0 && i < sourceValue.Length) { var scriptLanguage = sourceValue.Substring(0, i); var scriptText = sourceValue.Substring(i + 1); return(new ScriptBuilder { ScriptLanguage = scriptLanguage, ScriptText = scriptText }.Build()); } else { throw new FormatException("Expected format is 'ScriptLanguage|ScriptText'"); } } throw new NotSupportedException("The conversion cannot be performed."); }
/// <summary> /// Updates an AD object (also called by create after object is created) /// </summary> /// <param name="oclass"></param> /// <param name="directoryEntry"></param> /// <param name="attributes"></param> /// <param name="type"></param> /// <param name="config"></param> internal void UpdateADObject(ObjectClass oclass, DirectoryEntry directoryEntry, ICollection <ConnectorAttribute> attributes, UpdateType type, ActiveDirectoryConfiguration config) { if (oclass.Equals(ObjectClass.ACCOUNT)) { // translate attribute passed in foreach (ConnectorAttribute attribute in attributes) { // encountered problems when processing change password at the same time // as setting expired. It would be set to expired, but the change would // clear that. So we must ensure that expired comes last. if (OperationalAttributes.PASSWORD_EXPIRED_NAME.Equals(attribute.Name)) { continue; } AddConnectorAttributeToADProperties(oclass, directoryEntry, attribute, type); // Uncommenting the next line is very helpful in // finding mysterious errors. // Trace.TraceInformation("Committing after setting attribute {0} to {1}", attribute.Name, attribute.Value); // directoryEntry.CommitChanges(); } directoryEntry.CommitChanges(); // now do the password change. This is handled separately, because // it might be a user changing his own password, or it might be an // administrative change. GuardedString gsNewPassword = ConnectorAttributeUtil.GetPasswordValue(attributes); if (gsNewPassword != null) { GuardedString gsCurrentPassword = ConnectorAttributeUtil.GetCurrentPasswordValue(attributes); PasswordChangeHandler changeHandler = new PasswordChangeHandler(_configuration); if (gsCurrentPassword == null) { // just a normal password change changeHandler.changePassword(directoryEntry, gsNewPassword); } else { changeHandler.changePassword(directoryEntry, gsCurrentPassword, gsNewPassword); } UserAccountControl.Set(directoryEntry.Properties[ActiveDirectoryConnector.ATT_USER_ACOUNT_CONTROL], UserAccountControl.PASSWD_NOTREQD, false); directoryEntry.CommitChanges(); } // see note in loop above for explaination of this ConnectorAttribute expirePasswordAttribute = ConnectorAttributeUtil.Find( OperationalAttributes.PASSWORD_EXPIRED_NAME, attributes); if (expirePasswordAttribute != null) { AddConnectorAttributeToADProperties(oclass, directoryEntry, expirePasswordAttribute, type); directoryEntry.CommitChanges(); } /* * UserAccountControl.Set(directoryEntry.Properties[ActiveDirectoryConnector.ATT_USER_ACOUNT_CONTROL], * UserAccountControl.PASSWD_NOTREQD, false); */ directoryEntry.CommitChanges(); HandleNameAndContainerChange(type, directoryEntry, attributes, config); } else if (oclass.Equals(ActiveDirectoryConnector.groupObjectClass)) { // translate attribute passed in foreach (ConnectorAttribute attribute in attributes) { // Temporary // Trace.TraceInformation(String.Format("Setting attribute {0} to {1}", // attribute.Name, attribute.Value)); AddConnectorAttributeToADProperties(oclass, directoryEntry, attribute, type); // Uncommenting the next line is very helpful in // finding mysterious errors. // directoryEntry.CommitChanges(); } directoryEntry.CommitChanges(); HandleNameAndContainerChange(type, directoryEntry, attributes, config); } else if (oclass.Equals(ActiveDirectoryConnector.ouObjectClass)) { // translate attribute passed in foreach (ConnectorAttribute attribute in attributes) { // Temporary // Trace.TraceInformation(String.Format("Setting attribute {0} to {1}", // attribute.Name, attribute.Value)); AddConnectorAttributeToADProperties(oclass, directoryEntry, attribute, type); // Uncommenting the next line is very helpful in // finding mysterious errors. // directoryEntry.CommitChanges(); } directoryEntry.CommitChanges(); HandleNameAndContainerChange(type, directoryEntry, attributes, config); } else { String objectClassName = GetADObjectClass(oclass); // translate attribute passed in foreach (ConnectorAttribute attribute in attributes) { // Temporary // Trace.TraceInformation(String.Format("Setting attribute {0} to {1}", // attribute.Name, attribute.Value)); AddConnectorAttributeToADProperties(oclass, directoryEntry, attribute, type); // Uncommenting the next line is very helpful in // finding mysterious errors. // directoryEntry.CommitChanges(); } directoryEntry.CommitChanges(); HandleNameAndContainerChange(type, directoryEntry, attributes, config); } }
private static void DoSetKey(string key) { GuardedString str; if (key == null) { Console.Write("Please enter the new key: "); GuardedString v1 = ReadPassword(); Console.Write("Please confirm the new key: "); GuardedString v2 = ReadPassword(); if (!v1.Equals(v2)) { Console.WriteLine("Error: Key mismatch."); return; } str = v2; } else { str = new GuardedString(); foreach (char c in key) { str.AppendChar(c); } } Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings.Remove(Service.PROP_KEY); config.AppSettings.Settings.Add(Service.PROP_KEY, str.GetBase64SHA1Hash()); config.Save(ConfigurationSaveMode.Modified); Console.WriteLine("Key has been successfully updated."); }
public Uid Authenticate(ObjectClass objectClass, String username, GuardedString password, OperationOptions options) { return(((AuthenticationApiOp)this .GetOperationCheckSupported(SafeType <APIOperation> .Get <AuthenticationApiOp>())).Authenticate( objectClass, username, password, options)); }
private static GuardedString ReadPassword() { GuardedString rv = new GuardedString(); while (true) { ConsoleKeyInfo info = Console.ReadKey(true); if (info.Key == ConsoleKey.Enter) { Console.WriteLine(); rv.MakeReadOnly(); return rv; } else { Console.Write("*"); rv.AppendChar(info.KeyChar); } } }
/// <summary> /// Constructs a secure string from a char []. The char[] will /// be cleared out when finished. /// </summary> /// <param name="val">The characters to use. Will be cleared /// out.</param> /// <returns>A secure string representation</returns> public static GuardedString NewGuardedString(char[] val) { GuardedString rv = new GuardedString(); for (int i = 0; i < val.Length; i++) { rv.AppendChar(val[i]); val[i] = (char)0; } return rv; }
public virtual void TestFacadeEviction() { ConnectorServer server = ConnectorServer.NewInstance(); try { GuardedString str = new GuardedString(); str.AppendChar('c'); str.AppendChar('h'); str.AppendChar('a'); str.AppendChar('n'); str.AppendChar('g'); str.AppendChar('e'); str.AppendChar('i'); str.AppendChar('t'); #if DEBUG const int PORT = 58760; #else const int PORT = 58761; #endif server.MaxFacadeLifeTime = 1; server.Port = PORT; server.IfAddress = (IOUtil.GetIPAddress("127.0.0.1")); server.KeyHash = str.GetBase64SHA1Hash(); server.Start(); RemoteFrameworkConnectionInfo connInfo = new RemoteFrameworkConnectionInfo("127.0.0.1", PORT, str, false, null, 0); ConnectorInfoManager remoteManager = ConnectorInfoManagerFactory.GetInstance().GetRemoteManager(connInfo); ConnectorInfo remoteInfo = FindConnectorInfo(remoteManager, "1.0.0.0", "org.identityconnectors.testconnector.TstConnector"); ConnectorFacade remoteFacade = ConnectorFacadeFactory.GetInstance(). NewInstance(remoteInfo.CreateDefaultAPIConfiguration()); ManagedConnectorFacadeFactoryImpl managedFactory = (ManagedConnectorFacadeFactoryImpl)ConnectorFacadeFactory.GetManagedInstance(); // Assert it's empty Assert.IsNull(managedFactory.Find(remoteFacade.ConnectorFacadeKey)); remoteFacade.Schema(); // Assert it has one item Assert.IsNotNull(managedFactory.Find(remoteFacade.ConnectorFacadeKey)); Thread.Sleep(new TimeSpan(0, 2, 0)); // Assert it's empty Assert.IsNull(managedFactory.Find(remoteFacade.ConnectorFacadeKey)); } finally { server.Stop(); } }
private bool ProcessRequest() { CultureInfo locale; try { locale = (CultureInfo)_connection.ReadObject(); } catch (EndOfStreamException) { return(false); } //We can't set this because C# does not like language-neutral //cultures for CurrentCulture - this tends to blow up //TODO: think more about this... //Thread.CurrentThread.CurrentCulture = locale; Thread.CurrentThread.CurrentUICulture = locale; GuardedString key = (GuardedString)_connection.ReadObject(); bool authorized; try { authorized = key.VerifyBase64SHA1Hash(_server.KeyHash); } finally { key.Dispose(); } Org.IdentityConnectors.Framework.Common.Exceptions.InvalidCredentialException authException = null; if (!authorized) { authException = new Org.IdentityConnectors.Framework.Common.Exceptions.InvalidCredentialException("Remote framework key is invalid"); } Object requestObject = _connection.ReadObject(); if (requestObject is HelloRequest) { if (authException != null) { HelloResponse response = new HelloResponse(authException, null, null, null); _connection.WriteObject(response); } else { HelloResponse response = ProcessHelloRequest((HelloRequest)requestObject); _connection.WriteObject(response); } } else if (requestObject is OperationRequest) { if (authException != null) { OperationResponsePart part = new OperationResponsePart(authException, null); _connection.WriteObject(part); } else { OperationRequest opRequest = (OperationRequest)requestObject; OperationResponsePart part = ProcessOperationRequest(opRequest); _connection.WriteObject(part); } } else if (requestObject is EchoMessage) { if (authException != null) { //echo message probably doesn't need auth, but //it couldn't hurt - actually it does for test connection EchoMessage part = new EchoMessage(authException, null); _connection.WriteObject(part); } else { EchoMessage message = (EchoMessage)requestObject; Object obj = message.Object; String xml = message.ObjectXml; if (xml != null) { Console.WriteLine("xml: \n" + xml); Object xmlClone = SerializerUtil.DeserializeXmlObject(xml, true); xml = SerializerUtil.SerializeXmlObject(xmlClone, true); } EchoMessage message2 = new EchoMessage(obj, xml); _connection.WriteObject(message2); } } else { throw new Exception("Unexpected request: " + requestObject); } return(true); }
/// <summary> /// Does an administrative password change. The Directory /// entry must be created with username and password of /// a user with permission to change the password /// </summary> /// <param name="directoryEntry"></param> /// <param name="gsNewPassword"></param> internal void changePassword(DirectoryEntry directoryEntry, GuardedString gsNewPassword) { // decrypt and save the new password gsNewPassword.Access(setNewPassword); // get the native com object as an IADsUser, and set the // password IADsUser user = (IADsUser)directoryEntry.NativeObject; user.SetPassword(_newPassword); }
public Uid Authenticate(ObjectClass objectClass, String username, GuardedString password, OperationOptions options) { return ((AuthenticationApiOp)GetOperationCheckSupported(SafeType<APIOperation>.Get<AuthenticationApiOp>())).Authenticate( objectClass, username, password, options); }
/// <summary> /// Does a user password change. Must supply the currentpassword /// and the new password /// </summary> /// <param name="directoryEntry"></param> /// <param name="gsCurrentPassword"></param> /// <param name="gsNewPassword"></param> internal void changePassword(DirectoryEntry directoryEntry, GuardedString gsCurrentPassword, GuardedString gsNewPassword) { // decrypt and save the old nad new passwords gsNewPassword.Access(setNewPassword); gsCurrentPassword.Access(setCurrentPassword); // get the native com object as an IADsUser, and change the // password IADsUser user = (IADsUser)directoryEntry.NativeObject; user.ChangePassword(_currentPassword, _newPassword); }