major source structure and module name changes

This commit is contained in:
soochoi
2006-06-07 16:34:19 +00:00
parent 5c75241b4b
commit 1fa6f07e83
651 changed files with 0 additions and 0 deletions

81
micasad/AssemblyInfo.cs Normal file
View File

@@ -0,0 +1,81 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("micasad.exe")]
[assembly: AssemblyDescription("CASA Identity Store")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Novell, Inc")]
[assembly: AssemblyProduct("CASA")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.6.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

183
micasad/Makefile.am Normal file
View File

@@ -0,0 +1,183 @@
#######################################################################
#
# Copyright (C) 2006 Novell, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#######################################################################
if DEBUG
TARGET_CFG = Debug
CFLAGS += -v -w
CS_EXTRA_FLAGS = $(CSCFLAGS_DEBUG)
else
TARGET_CFG = Release
endif
SUBDIRS = lib startup
DIST_SUBDIRS = lib startup
DIST_SOURCES = *.cs
EXTRA_DIST = $(CSFILES) micasad* init/*.cs \
cache/*.cs common/*.cs communication/*.cs communication/win/*.cs \
init/*.cs init/*.resx lss/*.cs startup/micasad* verbs/*.cs \
test/cache/*.cs test/common/*.cs communication/*.cs communication/win/*.cs \
test/dependencies/*.dll test/verbs/*.cs test/*.txt \
startup/micasad* startup/casacfgpam startup/casaucfgpam
CASAROOT = ..
CASALIBDIR = $(CASAROOT)/$(LIB)
if LIB64
CASABINDIR = $(CASAROOT)/bin64
else
CASABINDIR = $(CASAROOT)/bin
endif
# handle Mono secondary dependencies
export MONO_PATH := $(MONO_PATH)
PLATFORMINDEPENDENTSOURCEDIR =
PLATFORMDEPENDENTSOURCEDIR = .
MODULE_NAME =micasad
MODULE_EXT =exe
CSFILES=$(srcdir)/AssemblyInfo.cs \
$(srcdir)/init/Main.cs \
$(srcdir)/init/AppHandler.cs \
$(srcdir)/common/RequestParser.cs \
$(srcdir)/common/SessionManager.cs \
$(srcdir)/common/User.cs \
$(srcdir)/common/UnixUser.cs \
$(srcdir)/common/UserIdentifier.cs \
$(srcdir)/common/UnixUserIdentifier.cs \
$(srcdir)/common/Constants.cs \
$(srcdir)/common/CSSSLogger.cs \
$(srcdir)/common/CSSSException.cs \
$(srcdir)/communication/IPCChannel.cs \
$(srcdir)/communication/CommunicationFactory.cs \
$(srcdir)/communication/UnixIPCChannel.cs \
$(srcdir)/communication/ICommunication.cs \
$(srcdir)/communication/UnixCommunication.cs \
$(srcdir)/cache/KeyChain.cs \
$(srcdir)/cache/Secret.cs \
$(srcdir)/cache/SecretStore.cs \
$(srcdir)/cache/KeyValue.cs \
$(srcdir)/cache/IKeychain.cs \
$(srcdir)/cache/ISecret.cs \
$(srcdir)/lss/FastRandom.cs \
$(srcdir)/lss/LocalStorage.cs \
$(srcdir)/lss/CASACrypto.cs \
$(srcdir)/lss/Rfc2898DeriveBytes.cs \
$(srcdir)/verbs/ISSVerb.cs \
$(srcdir)/verbs/GetSecretStoreInfo.cs \
$(srcdir)/verbs/OpenSecretStore.cs \
$(srcdir)/verbs/CloseSecretStore.cs \
$(srcdir)/verbs/RemoveSecretStore.cs \
$(srcdir)/verbs/AddKeyChain.cs \
$(srcdir)/verbs/RemoveKeyChain.cs \
$(srcdir)/verbs/WriteSecret.cs \
$(srcdir)/verbs/ReadSecret.cs \
$(srcdir)/verbs/RemoveSecret.cs \
$(srcdir)/verbs/EnumerateKeyChainIds.cs \
$(srcdir)/verbs/EnumerateSecretIds.cs \
$(srcdir)/verbs/SetMasterPassword.cs \
$(srcdir)/verbs/WriteKey.cs \
$(srcdir)/verbs/ReadKey.cs \
$(srcdir)/verbs/WriteBinaryKey.cs \
$(srcdir)/verbs/ReadBinaryKey.cs \
$(srcdir)/verbs/IsSecretPersistent.cs \
$(srcdir)/verbs/ObjectSerialization.cs \
$(srcdir)/test/cache/TestSecret.cs \
$(srcdir)/test/cache/TestKeyChain.cs \
$(srcdir)/test/cache/TestSecretStore.cs \
$(srcdir)/test/common/TestSessionManager.cs \
$(srcdir)/test/common/TestRequestParser.cs \
$(srcdir)/test/communication/TestUnixCommunication.cs \
$(srcdir)/test/verbs/TestOpenSecretStore.cs \
$(srcdir)/test/verbs/TestCloseSecretStore.cs \
$(srcdir)/test/verbs/TestEnumerateKeyChainIDs.cs \
$(srcdir)/test/verbs/TestEnumerateSecIDs.cs \
$(srcdir)/test/verbs/TestReadSecret.cs \
$(srcdir)/test/verbs/TestRemoveKeyChain.cs \
$(srcdir)/test/verbs/TestWriteSecret.cs
CSFILES_CSC := $(subst /,$(SEP),$(CSFILES))
CS_FLAGS = -d:LINUX -nowarn:169
CS_RESOURCES =
CS_LIBS =Mono.Posix.dll \
nunit.core.dll \
nunit.framework.dll \
nunit.extensions.dll \
nunit.util.dll \
nunit.mocks.dll \
$(CASALIBDIR)/$(TARGET_CFG)/Novell.CASA.Common.dll \
$(CASALIBDIR)/$(TARGET_CFG)/Novell.CASA.DataEngines.GnomeKeyring.dll
CS_LIBPATH = $(CASALIBDIR)/$(TARGET_CFG) $(srcdir)/test/dependencies
OBJDIR = ./$(TARGET_CFG)/$(LIB)
CUR_DIR := $(shell pwd)
all: $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
#
# Pattern based rules.
#
vpath %.cs $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
$(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT): $(OBJDIR) $(CSFILES)
@echo compiling $@ ...
$(CSC) $(CS_FLAGS) $(CS_EXTRA_FLAGS) $(CS_LIBPATH:%=-lib:%) $(CS_LIBS:%=/r:%) -out:$@ $(CSFILES_CSC)
cp -f $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT) $(CASABINDIR)/$(TARGET_CFG)/$(MODULE_NAME).$(MODULE_EXT)
#$(OBJDIR):
# [ -d $(OBJDIR) ] || mkdir -p $(OBJDIR)
# [ -d $(CASALIBDIR) ] || mkdir -p $(CASALIBDIR)
# [ -d $(CASALIBDIR)/$(TARGET_CFG) ] || mkdir -p $(CASALIBDIR)/$(TARGET_CFG)
$(OBJDIR):
[ -d $(OBJDIR) ] || mkdir -p $(OBJDIR)
[ -d $(CASABINDIR) ] || mkdir -p $(CASABINDIR)
[ -d $(CASABINDIR)/$(TARGET_CFG) ] || mkdir -p $(CASABINDIR)/$(TARGET_CFG)
install-exec-local: $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
$(mkinstalldirs) $(DESTDIR)$(libdir)
$(INSTALL_PROGRAM) $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT) $(DESTDIR)$(libdir)/
uninstall-local:
cd $(DESTDIR)$(libdir); rm -f $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
rmdir $(DESTDIR)$(libdir)
#installcheck-local: install
# $(mkinstalldirs) $(DESTDIR)$(libdir)
# $(INSTALL_PROGRAM) $(DESTDIR)$(libdir)
# cd $(DESTDIR)$(libdir); $(MONO)
clean-local:
if [ -d $(TARGET_CFG) ]; then rm -rf $(TARGET_CFG); fi
distclean-local:
maintainer-clean-local:
rm -f Makefile.in

37
micasad/cache/IKeychain.cs vendored Normal file
View File

@@ -0,0 +1,37 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
namespace sscs.cache
{
interface IKeychain
{
void AddSecret(Secret mySecret);
void RemoveSecret(String secretID);
Secret GetSecret(string secretID);
// IEnumerator getAllSecrets();
}
}

36
micasad/cache/ISecret.cs vendored Normal file
View File

@@ -0,0 +1,36 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace sscs.cache
{
interface ISecret
{
//Setter methods
void SetValue(byte[] key);
void SetKey(String newkey);
//Get methods
byte[] GetValue(String key);
string GetKey();
}
}

170
micasad/cache/KeyChain.cs vendored Normal file
View File

@@ -0,0 +1,170 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Threading;
using sscs.common;
namespace sscs.cache
{
class KeyChain : IKeychain
{
//We can have a Arraylist in case we dont need to look up via SecretID
// Hashtable has [SecretID(string), Secret(class)]
private Hashtable tSecretList = new Hashtable();
private Hashtable SecretList; // = Hashtable.Synchronized(tSecretList);
private string keyChainId;
private DateTime createdTime;
internal DateTime CreatedTime
{
get
{
return createdTime;
}
set
{
createdTime = value;
}
}
private DateTime accessedTime;
internal DateTime AccessedTime
{
get
{
return accessedTime;
}
set
{
accessedTime = value;
}
}
private DateTime modifiedTime;
internal DateTime ModifiedTime
{
get
{
return modifiedTime;
}
set
{
modifiedTime = value;
}
}
internal KeyChain()
{
SecretList = Hashtable.Synchronized(tSecretList);
}
internal KeyChain(string keyChainId)
{
SecretList = Hashtable.Synchronized(tSecretList);
this.keyChainId = keyChainId;
}
~KeyChain()
{
}
public void SetKey(string value)
{
keyChainId = value;
}
public void AddSecret(Secret mySecret)
{
try
{
mySecret.CreatedTime = DateTime.Now;
SecretList.Add((mySecret.GetKey()), mySecret);
this.ModifiedTime = DateTime.Now;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
}
public void RemoveSecret(String secretID)
{
// remove all keyvalues first, as to unlink reverse links
try
{
Secret secret = GetSecret(secretID);
secret.RemoveAllKeyValuePairs(this);
}
catch (Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
SecretList.Remove(secretID);
this.ModifiedTime = DateTime.Now;
}
public void RemoveAllSecrets()
{
SecretList.Clear();
}
public Secret GetSecret(string secretID)
{
if(SecretList.ContainsKey(secretID))
{
Secret secret = (Secret)SecretList[secretID];
secret.AccessedTime = DateTime.Now;
return secret;
}
else
throw new SecretNotFoundException(secretID);
}
internal string GetKey()
{
return keyChainId;
}
internal IEnumerator GetAllSecrets()
{
return SecretList.GetEnumerator();
}
internal int GetNumSecrets()
{
return SecretList.Count;
}
internal bool CheckIfSecretExists(string id)
{
if( SecretList.ContainsKey(id) )
return true;
else
return false;
}
}
}

234
micasad/cache/KeyValue.cs vendored Normal file
View File

@@ -0,0 +1,234 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
using System.Collections;
using Novell.CASA.MiCasa.Common;
namespace sscs.cache
{
public class KeyValue
{
public static int VALUE_TYPE_STRING = 0;
public static int VALUE_TYPE_BINARY = 1;
private int m_iValueType = VALUE_TYPE_STRING;
private string m_key;
public string Key
{
get
{
return m_key;
}
set
{
m_key = value;
}
}
private byte[] m_value;
public string GetValue()
{
return (DecryptValue());
}
public byte[] GetValueAsBytes()
{
return (DecyptValueAsBytes());
}
// this sets string values
public void SetValue(string sValue)
{
string oldValue = DecryptValue();
if (oldValue.Equals(sValue))
return;
else
{
byte[] newEncryptedValue = EncryptValue(sValue);
m_value = newEncryptedValue;
m_modified = DateTime.Now;
}
}
// this sets binary values
public void SetValue(byte[] baValue)
{
m_iValueType = VALUE_TYPE_BINARY;
m_value = EncryptValue(baValue);
m_modified = DateTime.Now;
}
/*
public string Value
{
get
{
// decrypt
return (DecryptValue());
}
set
{
byte[] newEncrypteValue = EncryptValue(value);
if ((newEncrypteValue != null) && (newEncrypteValue.Equals(m_value)))
return;
else
{
m_value = newEncrypteValue;
m_modified = DateTime.Now;
}
}
}
*/
private Hashtable mLinkedKeys = null; // = new Hashtable();
public void AddLink(LinkedKeyInfo linkedInfo)
{
if (mLinkedKeys == null)
mLinkedKeys = new Hashtable();
if(!mLinkedKeys.ContainsKey(linkedInfo.GetLinkID()))
mLinkedKeys.Add(linkedInfo.GetLinkID(), linkedInfo);
}
public void RemoveLink(string sLinkID)
{
// remove link
if (mLinkedKeys != null)
{
mLinkedKeys.Remove(sLinkID);
}
}
public Hashtable GetLinkedKeys()
{
return mLinkedKeys;
}
private DateTime m_dtEncryptTime = DateTime.Now;
private DateTime m_created;
public DateTime CreatedTime
{
get
{
return m_created;
}
}
private DateTime m_modified;
public DateTime ModifiedTime
{
get
{
return m_modified;
}
}
public KeyValue(string sKey, string sValue)
{
// NOTE: Order is important, do not change
m_created = m_modified = DateTime.Now;
m_key = sKey;
m_value = EncryptValue(sValue);
}
public KeyValue(string sKey, byte[] baValue)
{
// NOTE: Order is important, do not change
m_created = m_modified = DateTime.Now;
m_key = sKey;
m_value = EncryptValue(baValue);
m_iValueType = VALUE_TYPE_BINARY;
}
private byte[] EncryptValue(string sValue)
{
byte[] baValueClear = Encoding.Default.GetBytes(sValue);
return EncryptValue(baValueClear);
}
private byte[] EncryptValue(byte[] baValueClear)
{
// set encrypttime
m_dtEncryptTime = DateTime.Now;
return (XORValue(baValueClear));
}
private string DecryptValue()
{
byte[] baValueClear = DecyptValueAsBytes();
return Encoding.Default.GetString(baValueClear);
}
private byte[] DecyptValueAsBytes()
{
return XORValue(m_value);
}
private byte[] XORValue(byte[] baInput)
{
byte[] baOutput = new byte[baInput.Length];
Random ranNum = new Random(this.Key.GetHashCode());
for (int i=0; i<baInput.Length; i++)
{
baOutput[i] = (byte)((int)baInput[i] ^ ranNum.Next() ^ (~i) ^ m_dtEncryptTime.Ticks);
}
return baOutput;
}
public int GetValueType()
{
return m_iValueType;
}
public string ToXML()
{
StringBuilder sb = new StringBuilder();
sb.Append("<ENTRY>");
sb.Append("<KEY>");
sb.Append(m_key);
sb.Append("</KEY>");
sb.Append("<VALUE>");
sb.Append(m_value);
sb.Append("</VALUE>");
sb.Append("<MODIFIED>");
sb.Append(m_modified.Ticks);
sb.Append("</MODIFIED>");
sb.Append("</ENTRY>");
return sb.ToString();
}
}
}

403
micasad/cache/Secret.cs vendored Normal file
View File

@@ -0,0 +1,403 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
using System.Collections;
using Novell.CASA.MiCasa.Common;
namespace sscs.cache
{
class Secret : ISecret
{
private string secretID;
//private byte[] data;
string ePasswd ; // TBD
DateTime createdTime;
public DateTime CreatedTime
{
get
{
return createdTime;
}
set
{
createdTime = value;
}
}
DateTime accessedTime;
public DateTime AccessedTime
{
get
{
return accessedTime;
}
set
{
accessedTime = value;
}
}
DateTime modifiedTime;
public DateTime ModifiedTime
{
get
{
return modifiedTime;
}
set
{
modifiedTime = value;
}
}
private Hashtable htKeyValues = new Hashtable();
internal Secret()
{
}
internal Secret(string secretID)
{
this.secretID = secretID;
}
internal Secret(string secretID, byte[] data)
{
this.secretID = secretID;
//this.data = data;
// parse the data
ParseDataBuffer(data);
}
internal Secret(string secretID, byte[] data, string ePasswd)
{
this.secretID = secretID;
this.ePasswd = ePasswd;
ParseDataBuffer(data);
}
internal void ParseDataBuffer(byte[] data)
{
if (data != null)
{
UTF8Encoding dec = new UTF8Encoding();
string theData = dec.GetString(data);
char[] theChars = new char[2];
theChars[0] = '\n';
theChars[1] = '\0';
String[] keyValues = theData.Split(theChars);
char delimiter = '=';
foreach (string keyValue in keyValues)
{
int iLocation = keyValue.IndexOf(delimiter);
if (iLocation > 0)
{
String key = keyValue.Substring(0, iLocation);
String value = keyValue.Substring(iLocation + 1);
if (key != null && value != null)
this.SetKeyValue(key, value);
}
}
}
}
internal void SetEpasswd(string value)
{
ePasswd = value;
}
internal string GetEpasswd()
{
return ePasswd;
}
public void SetValue(byte[] data)
{
this.ModifiedTime = DateTime.Now;
ParseDataBuffer(data);
}
public void SetKey(String newkey)
{
//Validation TBD
this.secretID = newkey;
}
//Get methods
public byte[] GetValue(String key)
{
//validation TBD
//if (data == null)
{
StringBuilder sb = new StringBuilder();
IDictionaryEnumerator etor = (IDictionaryEnumerator)this.htKeyValues.GetEnumerator();
while(etor.MoveNext())
{
string sKey = (string)etor.Key;
KeyValue kv = (KeyValue)this.htKeyValues[sKey];
sb.Append(kv.Key);
sb.Append("=");
if (kv.GetValueType() ==(KeyValue.VALUE_TYPE_BINARY))
sb.Append("BINARY - Do not change");
else
sb.Append(kv.GetValue());
sb.Append('\n');
}
//sb.Append('\0');
UTF8Encoding enc = new UTF8Encoding();
this.AccessedTime = DateTime.Now;
return (enc.GetBytes(sb.ToString()));
}
//else
// return data;
}
public byte[] GetValue()
{
//validation TBD
this.AccessedTime = DateTime.Now;
return GetValue(null);
}
public string GetKey()
{
return secretID;
}
public void SetKeyValue(string key, string value)
{
KeyValue kv;
if (htKeyValues.Contains(key))
{
kv = (KeyValue)htKeyValues[key];
kv.SetValue(value);
}
else
{
kv = new KeyValue(key, value);
htKeyValues.Add(key, kv);
}
this.ModifiedTime = DateTime.Now;
}
public void SetKeyValue(string key, byte[] baValue)
{
KeyValue kv;
if (htKeyValues.Contains(key))
{
kv = (KeyValue)htKeyValues[key];
kv.SetValue(baValue);
}
else
{
kv = new KeyValue(key, baValue);
htKeyValues.Add(key, kv);
}
this.ModifiedTime = DateTime.Now;
}
public KeyValue GetKeyValue(string key)
{
this.AccessedTime = DateTime.Now;
if (htKeyValues.Contains(key))
{
KeyValue kv = (KeyValue)htKeyValues[key];
return kv;
}
else
return null;
}
internal void RemoveAllKeyValuePairs(KeyChain kc)
{
if (htKeyValues != null)
{
IDictionaryEnumerator enumer = htKeyValues.GetEnumerator();
while (enumer.MoveNext())
{
String key = (String)enumer.Key;
RemoveKeyValue(kc, key);
// refresh enumerator
enumer = htKeyValues.GetEnumerator();
}
}
}
public void RemoveKeyValue(KeyChain kc, string key)
{
if (htKeyValues.Contains(key))
{
// remove all reverse links first
RemoveReverseLinkedKeys(kc, key);
htKeyValues.Remove(key);
}
}
private void RemoveReverseLinkedKeys(KeyChain kc, string keyId)
{
Hashtable linkedKeys = GetLinkedKeys(keyId);
if (kc != null && linkedKeys != null)
{
IDictionaryEnumerator lkis = linkedKeys.GetEnumerator();
while (lkis.MoveNext())
{
LinkedKeyInfo lki = (LinkedKeyInfo)lkis.Value;
// look up reverse linked key
Secret secret = kc.GetSecret(lki.GetLinkedSecretID());
if (secret != null)
{
// look up linked key
KeyValue kv = secret.GetKeyValue(lki.GetLinkedKeyID());
kv.RemoveLink(secretID + ":" + keyId);
}
}
}
}
public DateTime GetKeyValueCreatedTime(string key)
{
if (htKeyValues.Contains(key))
{
KeyValue kv = (KeyValue)htKeyValues[key];
return kv.CreatedTime;
}
else
return (new DateTime(0));
}
public Hashtable GetLinkedKeys(string keyId)
{
if (htKeyValues.Contains(keyId))
{
KeyValue kv = (KeyValue)htKeyValues[keyId];
return kv.GetLinkedKeys();
}
else
return null;
}
public DateTime GetKeyValueModifiedTime(string key)
{
if (htKeyValues.Contains(key))
{
KeyValue kv = (KeyValue)htKeyValues[key];
return kv.ModifiedTime;
}
else
return (new DateTime(0));
}
public void MergeSecret(SecretStore store, Secret newSecret)
{
IDictionaryEnumerator etor = (IDictionaryEnumerator)newSecret.htKeyValues.GetEnumerator();
while(etor.MoveNext())
{
string sKey = (string)etor.Key;
// TODO: When we sync, we should consider modified time as well
KeyValue newKV = (KeyValue)newSecret.htKeyValues[sKey];
this.SetKeyValue(newKV.Key, newKV.GetValue());
}
etor = (IDictionaryEnumerator)newSecret.htKeyValues.GetEnumerator();
while(etor.MoveNext())
{
string sKey = (string)etor.Key;
if(!htKeyValues.Contains(sKey))
this.RemoveKeyValue(store.GetKeyChainDefault(), sKey);
}
}
public ArrayList GetKeyList()
{
IDictionaryEnumerator etor = (IDictionaryEnumerator)this.htKeyValues.GetEnumerator();
ArrayList list = new ArrayList();
if( null == etor )
{
return null;
}
while(etor.MoveNext())
{
string key = (string)etor.Key;
list.Add(key);
}
return list;
}
internal IDictionaryEnumerator GetKeyValueEnumerator()
{
if( htKeyValues != null)
return htKeyValues.GetEnumerator();
else
return null;
}
public string ToXML()
{
StringBuilder sb = new StringBuilder();
sb.Append("<SECRET>");
sb.Append("<ID>");
sb.Append(secretID);
sb.Append("</ID>");
sb.Append("<DATA>");
// enum the htKeyValues list
//IDictionaryEnumerator ienum = htKeyValues.GetEnumerator();
ICollection coll = htKeyValues.Values;
IDictionaryEnumerator ienum = (IDictionaryEnumerator)coll.GetEnumerator();
KeyValue kv = (KeyValue)ienum.Current;
while (kv != null)
{
sb.Append(kv.ToXML());
if (ienum.MoveNext())
kv = (KeyValue)ienum.Value;
else
kv = null;
}
sb.Append("</DATA>");
sb.Append("</SECRET>");
return sb.ToString();
}
}
}

780
micasad/cache/SecretStore.cs vendored Normal file
View File

@@ -0,0 +1,780 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Threading;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Security.Cryptography;
using System.Text;
using sscs.cache;
using sscs.common;
using sscs.constants;
using sscs.lss;
using sscs.crypto;
namespace sscs.cache
{
class SecretStore
{
internal string secretStoreName; // User name ?
internal int refCount;
private uint version;
private Hashtable tKeyChainList = new Hashtable();
private Hashtable keyChainList; //= Hashtable.Synchronized(tKeyChainList);
internal User user;
private Mutex ssMutex ; //reqd only for refCount
private int state; // Maintains the state of SS ( keychain
// type availability). TODO: Convert to a class.
private static int STATE_NOT_DEFINED = 0;
private static int STATE_OK = 1;
private static int STATE_LOCKED = 2;
private LocalStorage lss = null;
bool bIsStorePersistent = false;
private DateTime createTime;
public DateTime CreateTime
{
get
{
return createTime;
}
set
{
createTime = value;
}
}
~SecretStore()
{
ssMutex.Close();
}
internal SecretStore(User ssUser)
{
secretStoreName = ssUser.GetUserName();
version = 1;
state = STATE_NOT_DEFINED;
user = ssUser;
refCount = 0;
keyChainList = Hashtable.Synchronized(tKeyChainList);
ssMutex = new Mutex();
}
internal bool IsStorePersistent()
{
return bIsStorePersistent;
}
public bool StopPersistence()
{
if(lss != null && bIsStorePersistent == true)
{
lss.StopPersistence();
lss = null;
bIsStorePersistent = false;
}
return true;
}
public bool IsStoreLocked()
{
if (state == STATE_LOCKED)
return true;
else
return false;
}
public void LockStore()
{
state = STATE_LOCKED;
}
public bool UnlockStore(string sDesktopPassword, string sMasterPassword)
{
if (sDesktopPassword != null)
{
// verify Desktop password
//state = STATE_OK;
//return true;
}
if (sMasterPassword != null)
{
// verify MasterPassword
if (SetMasterPassword(sMasterPassword))
{
state = STATE_OK;
return true;
}
}
return false;
}
public bool IsDesktopPassword(string sDesktopPassword)
{
try
{
byte[] baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(sDesktopPassword, GetPasscodeByDesktopFilePath(), false);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
return true;
}
// try old salt
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(sDesktopPassword, GetPasscodeByDesktopFilePath(), true);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
return true;
}
}
catch
{
}
return false;
}
internal bool StartPersistenceByDesktopPasswd(string desktopPasswd)
{
CSSSLogger.DbgLog("StartPersistenceByDesktopPasswd - Called");
// make sure we have a user home directory
if (GetUserHomeDirectory() == null || GetUserHomeDirectory().Length < 1)
{
CSSSLogger.DbgLog("StartPersistenceByDesktopPasswd - No Home directory yet");
return false;
}
else
{
if (!Directory.Exists(GetUserHomeDirectory()))
{
CSSSLogger.DbgLog("StartPersistenceByDesktopPasswd - Home directory is not created yet");
return false;
}
}
try
{
byte[] baPasscode;
/* Persistence could have started because the user
* could have set master password.
*/
if(lss != null && bIsStorePersistent == true)
{
/* Verify passcode and if validation fails, rewrite
* desktop file.
*/
if(File.Exists(GetPasscodeByDesktopFilePath()))
{
}
else
{
/* Write the desktop passwd file.
*/
}
CSSSLogger.DbgLog(CSSSLogger.GetExecutionPath(this) + " Store is already persistent");
CSSSLogger.DbgLog("StartPersistenceByDesktopPasswd - Started");
return true;
}
if(!File.Exists(GetPasscodeByDesktopFilePath()))
{
if (File.Exists(GetPasscodeByMasterPasswdFilePath()))
{
// wait for the user to start the Persistence by entering MP
return false;
}
//Else passcode needs to be generated.
baPasscode = CASACrypto.GenerateMasterPasscodeUsingString(
desktopPasswd,
GetPasscodeByDesktopFilePath(),
GetValidationFilePath(),
user.UserIdentifier);
if( null == baPasscode )
return false;
if(!File.Exists(GetKeyFilePath()))
{
GenerateAndStoreEncryptionKey(baPasscode);
lss = new LocalStorage(this,baPasscode);
bIsStorePersistent = true;
return true;
}
}
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(desktopPasswd, GetPasscodeByDesktopFilePath(), false);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
lss = new LocalStorage(this,baPasscode);
bIsStorePersistent = true;
return true;
}
else
{
// try old encryption method
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(desktopPasswd, GetPasscodeByDesktopFilePath(), true);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
// rewrite file using new encryption
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, desktopPasswd, GetPasscodeByDesktopFilePath());
lss = new LocalStorage(this, baPasscode);
bIsStorePersistent = true;
return true;
}
else
{
lss = null;
bIsStorePersistent = false; //till masterPasswd is verified
}
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return false;
}
internal bool GenerateAndStoreEncryptionKey(byte[] baPasscode)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] key;
byte[] IV = new byte[16];
//Create a new key and initialization vector.
try
{
myRijndael.GenerateKey();
key = myRijndael.Key;
CASACrypto.StoreKeySetUsingMasterPasscode(key,IV,
baPasscode,
GetKeyFilePath());
}
catch (Exception e)
{
return false;
}
return true;
}
internal bool SetMasterPassword(string mPasswdFromIDK)
{
try
{
char[] trimChars = {'\0'};
string mPasswd = mPasswdFromIDK.TrimEnd(trimChars);
bool isVerifyOperation = false;
string mPasswdFileName = GetPasscodeByMasterPasswdFilePath();
byte[] baPasscode;
if(File.Exists(mPasswdFileName))
isVerifyOperation = true; //else it is a set operation.
string desktopPasswd = GetDesktopPasswd();
if(isVerifyOperation == false)
{
/* Here the master password file needs to be generated.
*/
if(desktopPasswd != null)
{
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(desktopPasswd, GetPasscodeByDesktopFilePath(), false);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(
baPasscode,
mPasswd,
GetPasscodeByMasterPasswdFilePath());
return true;
}
else
{
// try old method
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(desktopPasswd, GetPasscodeByDesktopFilePath(), true);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
// rewrite file using new method
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, desktopPasswd, GetPasscodeByDesktopFilePath());
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(
baPasscode,
mPasswd,
GetPasscodeByMasterPasswdFilePath());
return true;
}
else
{
//Probably desktop passwd has changed.
//But as even master passwd is being set only now,
//the persistent store is lost.
baPasscode = CASACrypto.GenerateMasterPasscodeUsingString(mPasswd, GetPasscodeByMasterPasswdFilePath(), GetValidationFilePath(), user.UserIdentifier);
if (baPasscode != null)
{
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, mPasswd, GetPasscodeByMasterPasswdFilePath());
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, desktopPasswd, GetPasscodeByDesktopFilePath());
if (File.Exists(GetPersistenceFilePath()))
{
File.Delete(GetPersistenceFilePath());
CSSSLogger.DbgLog("Removing the persistent storeas its meaningless now.");
}
if (bIsStorePersistent == false)
{
lss = new LocalStorage(this, baPasscode);
bIsStorePersistent = true;
}
return true;
}
else
{
return false;
}
}
}
//return true;
}//if a valid desktop Passwd is present - if ends here
else
{
/* If desktop passwd is not there and user sets
* master password.
*/
if(File.Exists(GetPersistenceFilePath()))
{
File.Delete(GetPersistenceFilePath());
CSSSLogger.DbgLog("Removing the persistent storeas its meaningless now. - Desktop passwd is not there and Master password is being set");
}
if(File.Exists((GetPasscodeByDesktopFilePath())))
{
File.Delete((GetPasscodeByDesktopFilePath()));
CSSSLogger.DbgLog("Removing the persistent storeas its meaningless now. - Desktop passwd is not there and Master password is being set");
}
baPasscode = CASACrypto.GenerateMasterPasscodeUsingString(mPasswd,GetPasscodeByMasterPasswdFilePath(),GetValidationFilePath(), user.UserIdentifier);
if(baPasscode != null)
{
if(!File.Exists(GetKeyFilePath()))
{
GenerateAndStoreEncryptionKey(baPasscode);
}
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode,mPasswd,GetPasscodeByMasterPasswdFilePath());
if( bIsStorePersistent == false )
{
lss = new LocalStorage(this,baPasscode);
bIsStorePersistent = true;
}
return true;
}
return false;
}
}//end of isVerifyOperation == false
else
{
/* Verify the master password. If verified, and if
* persistence has not started, start it.
*/
//Get the passcode from master passwd file and validate.
//If validation succeeds,start persistence.
if(desktopPasswd == null)
{
baPasscode = CASACrypto.DecryptMasterPasscodeUsingString(mPasswd, GetPasscodeByMasterPasswdFilePath(), false);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
if(bIsStorePersistent == false)
{
lss = new LocalStorage(this,baPasscode);
bIsStorePersistent = true;
}
return true;
}
else
{
// try validation, if it fails, try decryption using the old method
baPasscode = CASACrypto.DecryptMasterPasscodeUsingString(mPasswd, GetPasscodeByMasterPasswdFilePath(), true);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
// rewrite file
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, mPasswd, GetPasscodeByMasterPasswdFilePath());
if (bIsStorePersistent == false)
{
lss = new LocalStorage(this, baPasscode);
bIsStorePersistent = true;
}
return true;
}
else
{
return false;
}
}
}
else
{ //There are 2 cases - either desktop passwd has changed
//or it hasnt.
baPasscode = CASACrypto.GetMasterPasscodeUsingMasterPasswd(mPasswd, GetPasscodeByMasterPasswdFilePath(), false);
if(CASACrypto.ValidatePasscode(baPasscode,GetValidationFilePath()))
{
RewriteDesktopPasswdFile(baPasscode,desktopPasswd);
if(bIsStorePersistent == false)
{
lss = new LocalStorage(this,baPasscode);
bIsStorePersistent = true;
}
return true;
}
else
{
baPasscode = CASACrypto.GetMasterPasscodeUsingMasterPasswd(mPasswd, GetPasscodeByMasterPasswdFilePath(), true);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
RewriteDesktopPasswdFile(baPasscode, desktopPasswd);
if (bIsStorePersistent == false)
{
lss = new LocalStorage(this, baPasscode);
bIsStorePersistent = true;
}
return true;
}
return false;
}
}
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return false;
}//End of SetMasterPassword
internal bool RewriteDesktopPasswdFile(byte[] baPasscode, string desktopPasswd)
{
try
{
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, desktopPasswd, GetPasscodeByDesktopFilePath());
CSSSLogger.DbgLog("Re-encryted passcode with desktop passwd");
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return true;
}
internal byte[] GetPasscodeFromOldDesktopPasswd(string oldDesktopPasswd)
{
try
{
byte[] baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(oldDesktopPasswd, GetPasscodeByDesktopFilePath(), false);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
return baPasscode;
}
else
{
// try old method
baPasscode = CASACrypto.GetMasterPasscodeUsingDesktopPasswd(oldDesktopPasswd, GetPasscodeByDesktopFilePath(), true);
if (CASACrypto.ValidatePasscode(baPasscode, GetValidationFilePath()))
{
// rewrite file now
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, oldDesktopPasswd, GetPasscodeByDesktopFilePath());
return baPasscode;
}
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
/* This method would be called, when the user is setting his
* master passcode for the first time.
*/
internal bool SetMasterPasscode(string sMasterPasscode)
{
return true;
#if false
bool bRet = false;
try
{
if(!CASACrypto.CheckIfMasterPasscodeIsAvailable(desktopPasswd, GetPasswdFilePath()))
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] key;
byte[] IV = new byte[16];
//Create a new key and initialization vector.
myRijndael.GenerateKey();
key = myRijndael.Key;
CASACrypto.StoreKeySetUsingMasterPasscode(key,IV,sMasterPasscode,GetKeyFilePath());
//Store the master passcode encrypted with the desktopPasswd
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(sMasterPasscode, desktopPasswd, GetPasswdFilePath());
lss = new LocalStorage(this,sMasterPasscode);
bIsStorePersistent = true;
bRet = true;
}
else
{
//Console.WriteLine("Master passcode is already set");
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return bRet;
#endif
}
internal void IncrRefCount()
{
try
{
ssMutex.WaitOne();
refCount++;
ssMutex.ReleaseMutex();
CSSSLogger.DbgLog(CSSSLogger.GetExecutionPath(this) + " : RefCount = " + refCount);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
}
internal void DecrRefCount()
{
try
{
ssMutex.WaitOne();
refCount--;
ssMutex.ReleaseMutex();
CSSSLogger.DbgLog(CSSSLogger.GetExecutionPath(this) + " : RefCount = " + refCount);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
}
internal bool AddKeyChain(KeyChain keychain)
{
try
{
keychain.CreatedTime = DateTime.Now;
keyChainList.Add(keychain.GetKey(),keychain);
}
catch(Exception e)
{
CSSSLogger.DbgLog(e.ToString());
throw e;
}
CSSSLogger.DbgLog(CSSSLogger.GetExecutionPath(this) + " - Successfully added Keychain = "+ keychain.GetKey() + " length = "+ (keychain.GetKey()).Length);
return true;
}
internal bool RemoveKeyChain(string id)
{
keyChainList.Remove(id);
return true;
}
internal KeyChain GetKeyChainDefault()
{
return GetKeyChain("SSCS_SESSION_KEY_CHAIN_ID\0");
}
internal KeyChain GetKeyChain(string id)
{
if(keyChainList.ContainsKey(id))
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Keychain already exists.");
KeyChain kc = (KeyChain)(keyChainList[id]);
kc.AccessedTime = DateTime.Now;
return kc;
}
else
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Keychain doesnot exist.Returning null.");
throw new KeyChainDoesNotExistException(id);
}
}
internal bool CheckIfKeyChainExists(string id)
{
if(keyChainList.ContainsKey(id))
return true;
else
return false;
}
internal void UpdatePersistentStore()
{
if (lss != null)
lss.PersistStoreWithDelay();
}
/* This function would need to do any storage/cleanup required
* before removing a user session.
*/
internal bool CommitStore()
{
if(lss != null)
lss.PersistStore();
return true;
}
internal IEnumerator GetKeyChainEnumerator()
{
//TBD
// Return an Enumerator class which has all secrets in this keychain
return keyChainList.GetEnumerator();
}
internal void DumpSecretstore()
{
lock(keyChainList.SyncRoot)
{
IDictionaryEnumerator iter = (IDictionaryEnumerator)GetKeyChainEnumerator();
while( iter.MoveNext() )
{
int i = 0;
KeyChain kc = (KeyChain)iter.Value;
CSSSLogger.DbgLog("\nKeychain id = " + kc.GetKey());
CSSSLogger.DbgLog("Secret List is ");
IDictionaryEnumerator secIter = (IDictionaryEnumerator)(kc.GetAllSecrets());
while(secIter.MoveNext())
{
Secret secret = (Secret)secIter.Value;
CSSSLogger.DbgLog("Secret " + i.ToString() + " id = " + secret.GetKey() + " value = " + secret.GetValue() );
IDictionaryEnumerator etor = (IDictionaryEnumerator) secret.GetKeyValueEnumerator();
while(etor.MoveNext())
{
KeyValue kv = (KeyValue)etor.Value;
CSSSLogger.DbgLog("Key = " + kv.Key +" Value = " + kv.GetValue());
}
i++;
}
}
}
}
internal int GetSecretStoreState()
{
return state;
}
internal int GetNumKeyChains()
{
return keyChainList.Count;
}
internal bool SetSecretStoreState(int stateToSet)
{
//BrainShare Special Only - Only Session keychains state 1
state = STATE_OK;
return true;
}
internal bool ChangeMasterPassword(string sCurrentPWD, string sNewPWD)
{
string sMasterFilePath = GetPasscodeByMasterPasswdFilePath();
byte[] baPasscode = CASACrypto.GetMasterPasscodeUsingMasterPasswd(sCurrentPWD, sMasterFilePath, false);
if (baPasscode != null)
{
CASACrypto.EncryptAndStoreMasterPasscodeUsingString(baPasscode, sNewPWD, sMasterFilePath);
return true;
}
return false;
}
internal string GetDesktopPasswd()
{
try
{
string keyChainId = ConstStrings.SSCS_SESSION_KEY_CHAIN_ID + "\0";
KeyChain keyChain = GetKeyChain(keyChainId);
Secret secret = keyChain.GetSecret(ConstStrings.MICASA_DESKTOP_PASSWD);
string passwd = secret.GetKeyValue(ConstStrings.MICASA_DESKTOP_PASSWD_KEYNAME).GetValue();
return passwd;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
internal string GetUserHomeDirectory()
{
return user.GetUserHomeDir();
}
internal string GetKeyFilePath()
{
string homeDir = GetUserHomeDirectory();
return homeDir + ConstStrings.MICASA_KEY_FILE;
}
internal string GetPasscodeByDesktopFilePath()
{
string homeDir = GetUserHomeDirectory();
return homeDir + ConstStrings.MICASA_PASSCODE_BY_DESKTOP_FILE;
}
internal string GetPasscodeByMasterPasswdFilePath()
{
string homeDir = GetUserHomeDirectory();
return homeDir + ConstStrings.MICASA_PASSCODE_BY_MASTERPASSWD_FILE;
}
internal string GetPersistenceFilePath()
{
string homeDir = GetUserHomeDirectory();
return homeDir + ConstStrings.MICASA_PERSISTENCE_FILE;
}
internal string GetValidationFilePath()
{
string homeDir = GetUserHomeDirectory();
return homeDir + ConstStrings.MICASA_VALIDATION_FILE;
}
}
}

View File

@@ -0,0 +1,102 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
namespace sscs.common
{
//TBD
// All user defined exceptions will extend this class in future
internal class CSSSException : ApplicationException
{
internal string user;
internal CSSSException (string message)
{
}
}
internal class CommunicationException : ApplicationException
{
internal CommunicationException (String message) : base (message)
{
}
internal CommunicationException (String message, Exception inner) : base(message,inner)
{
}
}
internal class MessageFormatException : Exception
{
internal MessageFormatException (String message) : base (message)
{
}
internal MessageFormatException (String message, Exception inner) : base(message,inner)
{
}
}
internal class UserNotInSessionException : Exception
{
internal UserNotInSessionException (String message) : base (message)
{
CSSSLogger.DbgLog(message);
}
internal UserNotInSessionException (UserIdentifier user)
{
CSSSLogger.DbgLog("UserIdentifier is not in session table " + user.GetUID());
}
}
internal class KeyChainDoesNotExistException : Exception
{
internal KeyChainDoesNotExistException (String kId)
{
CSSSLogger.DbgLog("Keychain - " + kId + " not found");
}
}
internal class SecretNotFoundException : Exception
{
internal SecretNotFoundException (String sId)
{
CSSSLogger.DbgLog("SecretId - " + sId + " not found");
}
}
internal class CryptoException : ApplicationException
{
internal CryptoException(string msg)
{
CSSSLogger.DbgLog("Crypto exception : " + msg );
}
}
}

View File

@@ -0,0 +1,244 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
using System.Diagnostics;
using sscs.common;
using sscs.constants;
using System.IO;
using System.Threading;
namespace sscs.common
{
/*
* This ia a common logging facility for windows and Linux.
* This also is the common place to log all server logs and debug logs.
*/
class CSSSLogger
{
//private static CSSSLogger csssLog = null;
//private static string WINID = "Microsoft";
private static string engineLog = null;
#if DEBUG
private static string LINUXID = "Unix";
private static string debugLog = null;
private static Stream debugStream= null;
#endif
private static StreamWriter serverTrace= null;
private static Mutex dbgmutex = new Mutex();
static CSSSLogger()
{
#if DEBUG
if (Environment.OSVersion.ToString().StartsWith(LINUXID))
{
engineLog = ConstStrings.SSCS_LINUX_ENGINELOG;
debugLog = ConstStrings.SSCS_LINUX_DEBUGLOG;
}
else
{
engineLog = ConstStrings.SSCS_WIN_ENGINELOG;
debugLog = ConstStrings.SSCS_WIN_DEBUGLOG;
}
/* There is no set up for Server Trace
* open and close would be done when needed.
*/
// Set up for Debug
if( File.Exists( debugLog ) )
{
File.Delete( debugLog );
}
debugStream = File.Create(debugLog);
Debug.Listeners.Add(new TextWriterTraceListener(debugStream));
Debug.AutoFlush = true;
Debug.Indent();
Debug.WriteLine("Debug Log created");
#endif
}
public static void log(bool criticality, String message)
{
if (criticality) // Status message
WritetoServerLog(message);
else
DbgLog(message);
}
public static void log(bool criticality, System.Exception e)
{
if (criticality) // Status message
WritetoServerLog(e.ToString());
else
DbgLog(e.ToString());
}
public static void ExecutionTrace(Object obj)
{
#if DEBUG
StringBuilder message = null;
StackTrace st = null;
try
{
message = new StringBuilder();
st = new StackTrace(true);
}
catch( OutOfMemoryException e )
{
ExpLog(e.ToString());
throw e;
}
Type type = obj.GetType();
StackFrame sf = st.GetFrame(1);
message.Append(" ThreadID: ");
message.Append(Thread.CurrentThread.GetHashCode().ToString());
message.Append(" Executing Path: ");
message.Append(type.ToString());
message.Append(":");
if (sf != null)
message.Append(sf.GetMethod().ToString());
else
message.Append("Method unknown");
log( ConstStrings.DEBUG,message.ToString() );
#endif
}
public static void ExecutionTrace(Type type)
{
#if DEBUG
StringBuilder message = null;
StackTrace st = null;
try
{
message = new StringBuilder();
st = new StackTrace(true);
}
catch( OutOfMemoryException e )
{
ExpLog(e.ToString());
throw e;
}
StackFrame sf = st.GetFrame(1);
message.Append(" ThreadID: ");
message.Append(Thread.CurrentThread.GetHashCode().ToString());
message.Append(" Executing Path: ");
message.Append(type.ToString());
message.Append(":");
if (sf != null)
message.Append(sf.GetMethod().ToString());
else
message.Append("Method Unknown");
log( ConstStrings.DEBUG,message.ToString() );
#endif
}
public static string GetExecutionPath(Object obj)
{
StringBuilder message = null;
StackTrace st = null;
try
{
message = new StringBuilder();
st = new StackTrace(true);
}
catch( OutOfMemoryException e )
{
ExpLog(e.ToString());
throw e;
}
Type type = obj.GetType();
StackFrame sf = st.GetFrame(1);
message.Append(" ThreadID: ");
message.Append(Thread.CurrentThread.GetHashCode().ToString());
message.Append(" Executing Path: ");
message.Append(type.ToString());
message.Append("::");
if (sf != null)
message.Append(sf.GetMethod().ToString());
else
message.Append("Method unknown");
return message.ToString();
}
public static void logbreak()
{
dbgmutex.WaitOne();
Debug.WriteLine(" ") ;
Debug.WriteLine("----------------------------------------------------") ;
Debug.WriteLine(" ") ;
dbgmutex.ReleaseMutex();
}
// The log format is Time stamp : Machine name: Product name: Logging information
private static void WritetoServerLog( string message )
{
serverTrace = File.AppendText(engineLog);
serverTrace.Write("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
serverTrace.Write("CSSS");
serverTrace.Write(message);
serverTrace.Flush();
serverTrace.Close();
}
// The log format is Time stamp :Component name: Error description
public static void DbgLog(string message)
{
dbgmutex.WaitOne();
Debug.Write(DateTime.Now.ToLongTimeString());
Debug.Write(" " + DateTime.Now.ToLongDateString());
Debug.Write(":");
Debug.WriteLine(message);
// Debug.WriteLine(" ") ;
dbgmutex.ReleaseMutex();
}
public static void ExpLog(string message)
{
dbgmutex.WaitOne();
Debug.Write(DateTime.Now.ToLongTimeString());
Debug.Write(" " + DateTime.Now.ToLongDateString());
Debug.Write(": Exception encountered - ");
Debug.WriteLine(message);
Debug.WriteLine(" ") ;
StackTrace st = new StackTrace();
Debug.WriteLine(st.ToString());
dbgmutex.ReleaseMutex();
}
}
}

148
micasad/common/Constants.cs Normal file
View File

@@ -0,0 +1,148 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace sscs.constants
{
class IPCRetCodes
{
internal static int SSCS_REPLY_SUCCESS = 0;
internal static int SSCS_E_INVALID_MESSAGE = -1;
internal static int SSCS_E_VERSION_NOT_SUPPORTED = -2;
internal static int SSCS_E_SYSTEM_ERROR = -3;
internal static int SSCS_E_REPLY_NOT_AVAILABLE = -4;
internal static int SSCS_E_INVALID_KEYCHAIN = -5;
internal static int SSCS_E_INVALID_SECRETID = -6;
internal static int SSCS_E_KEYCHAIN_ALREADY_EXISTS = -7;
internal static int SSCS_E_MAX_KEYCHAINS_REACHED = -8;
internal static int SSCS_E_ADD_KEYCHAIN_FAILED = -9;
internal static int SSCS_E_NO_KEYCHAINS_EXIST = -10;
internal static int SSCS_E_KEYCHAIN_DOES_NOT_EXIST = -11;
internal static int SSCS_E_REMOVE_KEYCHAIN_FAILED = -12;
internal static int SSCS_E_WRITE_SECRET_FAILED = -13;
internal static int SSCS_E_ADDING_DEFAULT_KEYCHAIN_FAILED = -14;
internal static int SSCS_E_NO_SECRETS_EXIST = -15;
internal static int SSCS_E_REMOVE_SECRET_FAILED = -16;
internal static int SSCS_E_GET_SOCKET_PATH_FAILED = -17;
internal static int SSCS_E_CREATE_SOCKET_FAILED = -18;
internal static int SSCS_E_SECRETID_DOES_NOT_EXIST = -19;
internal static int SSCS_E_INVALID_INPUT = -20;
internal static int SSCS_E_SETTING_PASSCODE_FAILED = -21;
internal static int SSCS_PROMPT_PASSCODE = 1;
internal static int SSCS_STORE_IS_PERSISTENT = -22;
internal static int SSCS_STORE_IS_NOT_PERSISTENT = -23;
internal static int SSCS_SECRET_IS_PERSISTENT = -24;
internal static int SSCS_SECRET_IS_NOT_PERSISTENT = -25;
internal static int SSCS_SECRET_STORE_IS_LOCKED = -26;
}
internal class ReqMsgId
{
}
internal class RespMsgId
{
}
internal class RetCodes
{
internal static int SUCCESS = 0;
internal static int FAILURE = -1;
internal static int LOAD_HIDDEN_ONLY = 1;
internal static int LOAD_ALL_EXCEPT_HIDDEN = 2;
internal static int WRITE_HIDDEN_ONLY = 3;
internal static int WRITE_ALL_EXCEPT_HIDDEN = 4;
internal static int WRITE_ALL = 5;
}
internal class ConstStrings
{
internal static string SSCS_SESSION_KEY_CHAIN_ID = "SSCS_SESSION_KEY_CHAIN_ID";
internal static string SSCS_LOCAL_KEY_CHAIN_ID = "SSCS_LOCAL_KEY_CHAIN_ID";
internal static string SSCS_HIDDEN_LOCAL_KEYCHAIN_ID = "SSCS_HIDDEN_LOCAL_KEYCHAIN_ID";
internal static string SSCS_REMOTE_KEYCHAIN_ID = "SSCS_REMOTE_KEYCHAIN_ID";
internal static string SSCS_LOCAL_REMOTE_KEYCHAIN_ID = "SSCS_LOCAL_REMOTE_KEYCHAIN_ID";
//TBD , Need to look at Novell standard for the desktop
internal static string SSCS_WIN_ENGINELOG = "c:\\CSSS.log";
internal static string SSCS_WIN_DEBUGLOG = "c:\\CSSSDEBUG.log";
//TBD , Need to look at Novell standard for the desktop
internal static string SSCS_LINUX_ENGINELOG = "/var/log/localmessages";
internal static string SSCS_LINUX_DEBUGLOG = "/var/log/micasad_debug.log";
internal static string SSCS_LINUX_PIDFILE = "/var/run/micasad.pid";
internal static bool STATUS = true;
internal static bool DEBUG = false;
internal static string MICASA_DESKTOP_PASSWD = "SS_CredSet:Desktop\0";
// internal static string MICASA_DESKTOP_PASSWD_KEYNAME = "Password\0";
internal static string MICASA_DESKTOP_PASSWD_KEYNAME = "Password";
// The file where the key (encrypted with master passcode)
// would be stored
internal static string MICASA_PASSCODE_BY_DESKTOP_FILE = "/.miCASAPCByDesktop";
internal static string MICASA_PASSCODE_BY_MASTERPASSWD_FILE = "/.miCASAPCByMPasswd";
//The file where all possible passwds are cross encrypted and
//stored to provide multiple recovery points.
internal static string MICASA_KEY_FILE = "/.miCASAKey";
//The file where the user's credentials are persisted.
internal static string MICASA_PERSISTENCE_FILE = "/.miCASA";
//The file required to validate the desktop passwd
internal static string MICASA_VALIDATION_FILE = "/.miCASAValidate";
internal static string MICASA_VALIDATION_STRING = "miCASAValidationString";
}
internal class ConstFlags
{
internal static uint SSFLAGS_DESTROY_SESSION_F = 1;
}
internal class XmlConsts
{
internal static string miCASANode = "miCASA";
internal static string versionAttr = "version";
internal static string keyChainNode = "KeyChain";
internal static string idAttr = "id";
internal static string secretNode = "Secret";
internal static string valueNode = "Value";
internal static string timeNode = "Time";
internal static string createdTimeNode = "created";
internal static string modifiedTimeNode = "modified";
internal static string keyNode = "Key";
internal static string keyValueNode = "KeyValue";
internal static string linkedKeyNode = "LinkedKey";
internal static string linkedTargetSecretNode = "TargetSecret";
internal static string linkedTargetKeyNode = "TargetKey";
}
}

View File

@@ -0,0 +1,121 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.common;
/*
* After the bytes format is finalized for Windows this class might need to
* be modified..
* Depending upon impact either a new method can be invoked after platfrom
* check or a Factory pattern can be used to redesign this class.
*/
/*
* Namespaces used inside SSCS(main) will be of the following format "sscs.*"
* The NameSpaces available are....
* sscs.common [session, RequestParser]
* sscs.authentication
* sscs.verbs;[ssVerb, .......]
* sscs.cache [secretstore, keychain, secret]
* sscs.lss;
* sscs.synchronization;
* sscs.crypto
*/
namespace sscs.common
{
/* This class will be used to convert raw bytes to one of the SecretStore
* Verbs. Although there is no need to have many instances,
* this class will NOT be singleton class since we
* do not want a hit on performance (synchronization, obtaining locks,
* releasing locks...etc )
* Making it singleton is not giving us any advantage versus performance.
*/
internal class RequestParser
{
Hashtable msgIdMap = new Hashtable();
internal RequestParser()
{
msgIdMap.Add(1,"sscs.verbs.OpenSecretStore");
msgIdMap.Add(2,"sscs.verbs.CloseSecretStore");
msgIdMap.Add(3,"sscs.verbs.RemoveSecretStore");
msgIdMap.Add(4,"sscs.verbs.EnumerateKeyChainIds");
msgIdMap.Add(5,"sscs.verbs.AddKeyChain");
msgIdMap.Add(6,"sscs.verbs.RemoveKeyChain");
msgIdMap.Add(7,"sscs.verbs.EnumerateSecretIds");
msgIdMap.Add(8,"sscs.verbs.ReadSecret");
msgIdMap.Add(9,"sscs.verbs.WriteSecret");
msgIdMap.Add(10,"sscs.verbs.RemoveSecret");
msgIdMap.Add(11,"sscs.verbs.GetSecretStoreInfo");
msgIdMap.Add(12,"sscs.verbs.GetKeyChainInfo");
msgIdMap.Add(13,"sscs.verbs.LockCache");
msgIdMap.Add(14,"sscs.verbs.UnLockCache");
msgIdMap.Add(15,"sscs.verbs.SetMasterPasscode");
msgIdMap.Add(16,"sscs.verbs.ReadKey");
msgIdMap.Add(17,"sscs.verbs.WriteKey");
msgIdMap.Add(18,"sscs.verbs.SetMasterPassword");
msgIdMap.Add(19,"sscs.verbs.IsSecretPersistent");
msgIdMap.Add(20,"sscs.verbs.ObjectSerialization");
msgIdMap.Add(21,"sscs.verbs.WriteBinaryKey");
msgIdMap.Add(22,"sscs.verbs.ReadBinaryKey");
}
/* Processes the request and returns the corrrect SSverb.
* This interface works on the class member rawbytes and
* returns the result.
*/
internal SSVerb ParseRequest(byte[] rawbytes)
{
if (rawbytes == null)
throw new FormatException("Message format incorrect");
String className = GetClassName(rawbytes);
SSVerb theVerb = (SSVerb)Activator.CreateInstance(null, className ).Unwrap();
theVerb.SetMessageContent(rawbytes);
/*
* TBD: We can send the activation params in the same call.
*/
//SSVerb theVerb = (SSVerb)Activator.CreateInstance(Type.GetType(className)).Unwrap();
return theVerb;
}
private string GetClassName(byte[] ipcbytes)
{
/*
* Read first two bytes and get ushort
* Look up table and send class name
*/
ushort msgId = BitConverter.ToUInt16(ipcbytes,0);
return ((String)(msgIdMap[(int)msgId]));
}
}
}

View File

@@ -0,0 +1,377 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Threading;
using System.IO;
using sscs.cache;
using sscs.common;
using sscs.constants;
using System.Diagnostics;
namespace sscs.common
{
class SessionManager
{
private static readonly SessionManager sessionManager = new SessionManager();
private static Mutex mutex = new Mutex();
private static Hashtable sessionTable = new Hashtable();
private static Thread tJanitor = null;
private static int JANITOR_SLEEP_TIME = 1000*60*5; // 5 minutes
private SessionManager()
{
#if LINUX
if (tJanitor == null)
{
tJanitor = new Thread(new ThreadStart(CleanUpSessionsThread));
tJanitor.Start();
}
#endif
}
~SessionManager()
{
if (tJanitor != null)
{
tJanitor.Abort();
tJanitor.Join();
}
mutex.Close();
}
internal static SessionManager GetSessionManager
{
get
{
return sessionManager;
}
}
internal static SecretStore CreateUserSession(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
SecretStore ss;
userId.PrintIdentifier();
try
{
ss = GetUserSecretStore(userId);
ss.IncrRefCount();
ss.CreateTime = DateTime.Now;
return ss;
}
catch(UserNotInSessionException e)
{
// Would create either windows/unix user
// depending on the platform.
User user = User.CreateUser(userId);
mutex.WaitOne();
sessionTable.Add(userId,user);
mutex.ReleaseMutex();
ss = user.GetSecretStore();
ss.IncrRefCount();
ss.CreateTime = DateTime.Now;
return ss;
}
}
internal static bool RemoveUserSession(UserIdentifier userId, bool destroySession)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
mutex.WaitOne();
SecretStore ss = GetUserSecretStore(userId);
ss.DecrRefCount();
// We must keep the cache alive, and destroy it on
// a logout event
//if( 0 == ss.refCount )
if (destroySession)
{
CSSSLogger.DbgLog("Removing the user session of " + userId.GetUID());
ss.CommitStore();
sessionTable.Remove(userId);
}
mutex.ReleaseMutex();
return true;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return false;
}
internal static bool CheckIfUserSessionExists(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
mutex.WaitOne();
if( sessionTable.ContainsKey(userId) )
{
mutex.ReleaseMutex();
return true;
}
else
{
mutex.ReleaseMutex();
return false;
}
}
internal static SecretStore GetUserSecretStore(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
userId.PrintIdentifier();
ListActiveUserSessions();
mutex.WaitOne();
if( sessionTable.ContainsKey(userId) )
{
User user = (User)sessionTable[userId];
SecretStore ss = user.GetSecretStore();
// start persistent if not going yet
if (!ss.IsStorePersistent())
{
string sDesktopPWD = ss.GetDesktopPasswd();
if (sDesktopPWD != null)
ss.StartPersistenceByDesktopPasswd(sDesktopPWD);
}
mutex.ReleaseMutex();
return ss;
}
else
{
mutex.ReleaseMutex();
throw new UserNotInSessionException(userId);
}
}
internal static DateTime GetSessionCreateTime(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
mutex.WaitOne();
if( sessionTable.ContainsKey(userId) )
{
User user = (User)sessionTable[userId];
SecretStore ss = user.GetSecretStore();
mutex.ReleaseMutex();
return ss.CreateTime;
}
else
{
mutex.ReleaseMutex();
throw new UserNotInSessionException(userId);
}
}
internal static void ListActiveUserSessions()
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
mutex.WaitOne();
IDictionaryEnumerator etor = sessionTable.GetEnumerator();
int i = 0;
while(etor.MoveNext())
{
i++;
/*
CSSSLogger.DbgLog("Listing Active User Sessions");
Console.WriteLine(etor.Key);
Console.WriteLine((((SecretStore)(etor.Value)).secretStoreName + ":" + ((SecretStore)(etor.Value)).refCount);
*/
}
mutex.ReleaseMutex();
}
private static void CleanUpSessionsThread()
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
while (true)
{
// enumerate users in the session
IEnumerator etor;
ICollection keys = sessionTable.Keys;
if (keys != null)
{
etor = keys.GetEnumerator();
while(etor.MoveNext())
{
UserIdentifier userIdentifier = (UserIdentifier)etor.Current;
// check if this user still has
// processes running
if(CheckAndDestroySession(userIdentifier,false))
{
/* If at least 1 session was removed,
* the etor must be
* re-initiated, else
* Invalidoperationexception will be
* thrown.
*/
keys = sessionTable.Keys;
if( null == keys )
break;
else
{
etor = keys.GetEnumerator();
}
}
}//while etor.MoveNext ends here.
}
Thread.Sleep(JANITOR_SLEEP_TIME);
} //while true ends here.
}
catch(ThreadAbortException e)
{
CSSSLogger.DbgLog("Janitor thread is going down.");
}
}//Method ends here.
/* As the pam module does a seteuid(), when is ps is
* execed it would appear as if the user owns the process.
* Hence, if this method is called from CloseSecretStore
* verb ( that would have been initiated from the pam
* module with ssFlags = 1), then if number of processes
* is one, then delete the session.
*/
internal static bool CheckAndDestroySession(UserIdentifier userID, bool calledFromClose)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
int iUID = userID.GetUID();
bool retVal = false;
Process myProcess = null;
StreamReader myStreamReader = null;
if (iUID != -1)
{
// make the 'ps h U UID' call
try
{
myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("ps" );
myProcessStartInfo.Arguments = "h U " + iUID.ToString();
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
myProcess.WaitForExit();
myStreamReader = myProcess.StandardOutput;
// Read the standard output of the spawned process.
string myString = myStreamReader.ReadLine();
int numProcs = 0;
// determine if user has more than 1 process still running
while( myString != null)
{
if(numProcs > 1)
{
break;
}
numProcs++;
myString = myStreamReader.ReadLine();
}
do
{
/* If this has been called from
* CloseSecretStore verb,
* verb, the session must be deleted.
*/
if( calledFromClose )
{
RemoveUserSession(userID, true);
retVal = true;
break;
}
/* If the session was created during login,
* and the janitor thread starts processing
* before user login is completed, we need
* maintain the user session (say for 5 mts).
*/
if( (numProcs == 0) && (CheckIfLoginTimeSession(userID)) )
{
retVal = false;
break;
}
/* If the user does not own any processes and
* if this method has not been called from
* CloseSecretStore verb, it implies that a user
* background process, which existed during user
* logout has died now.
* So, clean the user session.
*/
if ( (numProcs == 0) && (!calledFromClose) )
{
RemoveUserSession(userID, true);
retVal = true;
break;
}
}while(false);
/*
myProcess.Close();
myStreamReader.Close();
*/
}
catch (Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
finally
{
if( myProcess != null )
myProcess.Close();
if( myStreamReader != null )
myStreamReader.Close();
}
}
return retVal;
}
internal static bool CheckIfLoginTimeSession(UserIdentifier userId)
{
if( ((TimeSpan)(DateTime.Now - GetSessionCreateTime(userId))).TotalMinutes < 3 )
{
return true;
}
else
return false;
}
}
}

View File

@@ -0,0 +1,66 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.IO;
using sscs.cache;
using sscs.common;
using sscs.constants;
namespace sscs.common
{
internal class UnixUser : User
{
internal UnixUser()
{
}
internal UnixUser(UserIdentifier unixUserId)
{
userId = unixUserId;
secretStore = new SecretStore(this);
}
override internal void SetUserName(string username)
{
userName = username;
}
override internal string GetUserName()
{
return userName;
}
override internal string GetUserHomeDir()
{
uint uid = (uint)userId.GetUID();
Mono.Unix.UnixUserInfo uui = new Mono.Unix.UnixUserInfo(uid);
return uui.HomeDirectory;
}
}
}

View File

@@ -0,0 +1,58 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace sscs.common
{
internal class UnixUserIdentifier : UserIdentifier
{
private int uid;
internal UnixUserIdentifier(int uid)
{
this.uid = uid;
}
public override bool Equals(Object obj)
{
UnixUserIdentifier u = (UnixUserIdentifier)obj;
if (u.uid == uid)
return true;
else
return false;
}
public override int GetHashCode()
{
return uid.GetHashCode();
}
public void PrintIdentifier()
{
// Console.WriteLine("UnixUserIdentifier : uid is {0}",uid);
}
public int GetUID()
{
return uid;
}
}
}

71
micasad/common/User.cs Normal file
View File

@@ -0,0 +1,71 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using sscs.cache;
namespace sscs.common
{
abstract class User
{
protected UserIdentifier userId;
public UserIdentifier UserIdentifier
{
get
{
return userId;
}
}
protected SecretStore secretStore;
protected string home;
/* Change the protection level after getting the latest requirements */
protected string userName = null;
abstract internal void SetUserName(string userName);
abstract internal string GetUserName();
abstract internal string GetUserHomeDir();
internal SecretStore GetSecretStore()
{
return secretStore;
}
internal static User CreateUser(UserIdentifier userId)
{
User user = null;
#if LINUX
user = new UnixUser(userId);
#endif
#if W32
user = new WinUser(userId);
#endif
return user;
}
}
}

View File

@@ -0,0 +1,35 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
namespace sscs.common
{
public interface UserIdentifier
{
void PrintIdentifier();
int GetUID();
}
}

122
micasad/common/WinUser.cs Normal file
View File

@@ -0,0 +1,122 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.IO;
using Microsoft.Win32;
using sscs.cache;
using sscs.common;
using sscs.constants;
namespace sscs.common
{
internal class WinUser : User
{
private string m_sUserHome = "";
internal WinUser()
{
}
internal WinUser(UserIdentifier winUserId)
{
userId = winUserId;
secretStore = new SecretStore(this);
}
override internal void SetUserName(string username)
{
userName = username;
}
override internal string GetUserName()
{
return userName;
}
/* A method to find the user's home dir on windows needs to be added.
*/
override internal string GetUserHomeDir()
{
CSSSLogger.DbgLog("WinUser:GetUserHomeDir - Entered");
if (m_sUserHome == null || m_sUserHome.Length < 1)
{
CSSSLogger.DbgLog("WinUser:GetUserHomeDir is empty");
//Console.WriteLine("read registry");
// get the users home drive and homepath from the registry
//
string sSIDString = ((WinUserIdentifier)userId).GetSID();
// look up Profile path
// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-1757981266-436374069-725345543-1006]
CSSSLogger.DbgLog("Reading Reg: SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\" + sSIDString);
string sProfile = ReadRegKey(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\" + sSIDString, "ProfileImagePath");
if (sProfile == null)
CSSSLogger.DbgLog("WinUser:GetUserHomeDir get Profile return null");
else
m_sUserHome = sProfile;
//string sHomeDrive = ReadRegKey(Registry.Users, sSIDString+"\\Volatile Environment", "HOMEDRIVE");
//string sHomeDir = ReadRegKey(Registry.Users, sSIDString+"\\Volatile Environment", "HOMEPATH");
//m_sUserHome = sHomeDrive+sHomeDir;
//Console.WriteLine("Homedir: "+ m_sUserHome);
}
CSSSLogger.DbgLog("WinUser:GetUserHomeDir - Exited: "+m_sUserHome);
return m_sUserHome;
}
private string ReadRegKey(RegistryKey rk, string sSubKey, string KeyName)
{
// Opening the registry key
// RegistryKey rk = Registry.Users;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(sSubKey);
// If the RegistrySubKey doesn't exist -> (null)
if ( sk1 == null )
{
return null;
}
else
{
try
{
// If the RegistryKey exists I get its value
// or null is returned.
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception e)
{
//ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
return null;
}
}
}
}
}

View File

@@ -0,0 +1,84 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace sscs.common
{
internal class WinUserIdentifier : UserIdentifier
{
private int uidLow;
private int uidHigh;
private string m_sSID = "";
internal WinUserIdentifier(int uidLowPart, int uidHighPart, string sSID)
{
this.uidLow = uidLowPart;
this.uidHigh = uidHighPart;
this.m_sSID = sSID;
}
internal WinUserIdentifier(int uidLowPart, int uidHighPart)
{
this.uidLow = uidLowPart;
this.uidHigh = uidHighPart;
}
internal string GetSID()
{
return m_sSID;
}
public override bool Equals(Object obj)
{
WinUserIdentifier u = (WinUserIdentifier)obj;
if ((u.uidLow == uidLow) && (u.uidHigh == uidHigh))
{
// we have a match, set the SID if we can
if ((this.m_sSID.Length < 1) && (u.GetSID().Length>0))
{
CSSSLogger.DbgLog("******** WinUserIdentifier: Updating the SID *********");
this.m_sSID = u.GetSID();
}
return true;
}
else
return false;
}
public override int GetHashCode()
{
return uidLow.GetHashCode();
}
public void PrintIdentifier()
{
// Console.WriteLine("WinUserIdentifier : uid is {0}",uid);
}
public int GetUID()
{
return -1;
}
}
}

View File

@@ -0,0 +1,52 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
/* This class would have only static methods.
*/
namespace sscs.communication
{
class CommunicationFactory
{
/* Make the constructor private, to avoid instances of this
* class.
*/
private CommunicationFactory()
{
}
/* This method must check for platform and return
* an appropriate class. As of now, it assumes platform as Linux.
*/
public static Communication CreateCommunicationEndPoint()
{
#if LINUX
return( new UnixCommunication());
#endif
#if W32
return (new WinCommunication());
#endif
}
}
}

View File

@@ -0,0 +1,37 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
/* This is an interface which would be implemented
* by UnixCommunication and WinCommunication.
*/
namespace sscs.communication
{
interface Communication
{
void StartCommunicationEndPoint();
void CloseCommunicationEndPoint();
}
}

View File

@@ -0,0 +1,62 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Net;
using System.Net.Sockets;
#if W32
using AppModule.NamedPipes;
#endif
using sscs.common;
namespace sscs.communication
{
abstract class IPCChannel
{
/* This must check for the platform and return an
* appropriate IPCChannel.
*/
#if LINUX
internal static IPCChannel Create(Socket socket)
{
if(( (int)Environment.OSVersion.Platform) == 128)
return (new UnixIPCChannel(socket) );
else
return null;
}
#endif
#if W32
internal static IPCChannel Create(ServerPipeConnection serverPipe)
{
return (new WinIPCChannel(serverPipe));
}
#endif
abstract internal UserIdentifier GetIPCChannelUserId();
abstract internal int Read(byte[] buf);
abstract internal byte[] Read();
abstract internal int Write(byte[] buf);
abstract internal void Close();
}
}

View File

@@ -0,0 +1,167 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Net;
using System.Net.Sockets;
using Mono.Unix;
using Mono.Unix.Native;
using System.IO;
using System.Text;
using System.Threading;
using sscs.common;
using sscs.constants;
namespace sscs.communication
{
/* Platform specific class which implements
* the 'Communication' interface.
*/
class UnixCommunication : Communication
{
private Socket listeningSocket;
private Socket connectedSocket;
private string socketFileName = "/tmp/.novellCASA";
private Mono.Unix.UnixEndPoint sockEndPoint;
private ManualResetEvent eventVar = null;
//Methods
internal UnixCommunication()
{
CSSSLogger.ExecutionTrace(this);
Syscall.umask(0);
if(File.Exists(socketFileName))
{
File.Delete(socketFileName);
}
listeningSocket = new Socket( AddressFamily.Unix,
SocketType.Stream,
ProtocolType.IP );
sockEndPoint = new Mono.Unix.UnixEndPoint(socketFileName);
eventVar = new ManualResetEvent(true);
}
~UnixCommunication()
{
CSSSLogger.ExecutionTrace(this);
eventVar.Close();
CloseCommunicationEndPoint();
}
// This code executes in the listening thread.
public void StartCommunicationEndPoint()
{
CSSSLogger.ExecutionTrace(this);
try
{
UnixFileSystemInfo sockFileInfo = new UnixFileInfo(socketFileName);
UnixUserInfo sockFileOwner = sockFileInfo.OwnerUser;
// check if ROOT is the owner of the file: /tmp/.novellCASA
if (sockFileOwner.UserId != 0)
{
File.Delete(socketFileName);
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
listeningSocket.Bind(sockEndPoint);
listeningSocket.Listen(50);
while(true)
{
try
{
eventVar.Reset();
listeningSocket.BeginAccept(new AsyncCallback(ListenCb),
listeningSocket);
eventVar.WaitOne();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
}
}
public void CloseCommunicationEndPoint()
{
CSSSLogger.ExecutionTrace(this);
listeningSocket.Close();
if(File.Exists( socketFileName ))
File.Delete(socketFileName);
}
// On receipt of a new client, this method is called.
private void ListenCb (IAsyncResult state)
{
try
{
CSSSLogger.ExecutionTrace(this);
connectedSocket = ((Socket)state.AsyncState).EndAccept (state);
eventVar.Set();
ServiceClient();
}
catch(Exception e)
{
/* All resources would have been cleaned up before reaching
* here.
*/
CSSSLogger.ExpLog(e.ToString());
}
/* End of thread function */
}
private void ServiceClient()
{
CSSSLogger.ExecutionTrace(this);
IPCChannel ipcChannel = IPCChannel.Create(connectedSocket);
AppHandler appHandler = new AppHandler(ipcChannel);
try
{
int retVal = appHandler.ServiceApp();
if( retVal != RetCodes.SUCCESS )
CSSSLogger.DbgLog("Servicing client failed.");
}
catch( Exception e )
{
CSSSLogger.ExpLog(e.ToString());
}
finally
{
ipcChannel.Close();
}
}
}
}

View File

@@ -0,0 +1,166 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Net;
using System.Net.Sockets;
using Mono.Unix;
using System.IO;
using System.Text;
using sscs.common;
using sscs.verbs;
using sscs.constants;
namespace sscs.communication
{
class UnixIPCChannel : IPCChannel
{
// Data
private Socket clientSocket;
private UnixUserIdentifier userId;
//Methods
internal UnixIPCChannel(Socket connectedSocket)
{
CSSSLogger.ExecutionTrace(this);
clientSocket = connectedSocket;
Mono.Unix.PeerCred cred;
cred = new Mono.Unix.PeerCred(connectedSocket);
userId = new UnixUserIdentifier(cred.UserID);
}
override internal UserIdentifier GetIPCChannelUserId()
{
CSSSLogger.ExecutionTrace(this);
return userId;
}
private UnixIPCChannel()
{
CSSSLogger.ExecutionTrace(this);
}
~UnixIPCChannel()
{
CSSSLogger.ExecutionTrace(this);
clientSocket.Close();
}
override internal int Read(byte[] buf)
{
return 0;
}
override internal byte[] Read()
{
CSSSLogger.ExecutionTrace(this);
int bytesRecvd = 0;
try
{
byte[] msgIdBytes = new byte[2];
bytesRecvd = clientSocket.Receive(msgIdBytes);
if( 0 == bytesRecvd )
{
return null;
}
if( bytesRecvd < 0 ) // IPC is fine and Client had some problem
{
throw new CommunicationException("Client has not sent data.");
}
byte[] msgLenBytes = new byte[4];
bytesRecvd = clientSocket.Receive(msgLenBytes);
if( 0 == bytesRecvd )
{
return null;
}
if( bytesRecvd < 0 ) // IPC is fine and Client had some problem
{
throw new CommunicationException("Client has not sent data.");
}
byte[] bufToReturn = null;
uint msgLen = BitConverter.ToUInt32(msgLenBytes,0);
if( msgLen > 6 )
{
byte[] buf = new byte[msgLen - 6];
bytesRecvd = clientSocket.Receive (buf);
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Bytes received is " + bytesRecvd);
if( 0 == bytesRecvd )
{
return null;
}
if( bytesRecvd < 0 ) // IPC is fine and Client had some problem
{
throw new CommunicationException("Client has not sent data.");
}
bufToReturn = new byte[msgLen];
Array.Copy(msgIdBytes,bufToReturn,2);
Array.Copy(msgLenBytes,0,bufToReturn,2,4);
Array.Copy(buf,0,bufToReturn,6,buf.Length);
return bufToReturn;
}
else
{
bufToReturn = new byte[6];
Array.Copy(msgIdBytes,bufToReturn,2);
Array.Copy(msgLenBytes,0,bufToReturn,2,4);
return bufToReturn;
}
}
catch(CommunicationException e)
{
throw e;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new CommunicationException(e.ToString());
}
}
override internal int Write(byte[] buf)
{
try
{
CSSSLogger.ExecutionTrace(this);
int bytesSent = clientSocket.Send(buf);
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " - Bytes sent is " + bytesSent);
return bytesSent;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
return -1;
}
}
override internal void Close()
{
CSSSLogger.ExecutionTrace(this);
clientSocket.Close();
}
}
}

View File

@@ -0,0 +1,61 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using sscs.common;
using sscs.constants;
using AppModule.InterProcessComm;
using AppModule.NamedPipes;
using sscs.communication.win;
namespace sscs.communication
{
/// <summary>
/// Summary description for WinCommunication.
/// </summary>
public class WinCommunication : Communication
{
public static IChannelManager PipeManager;
public WinCommunication()
{
PipeManager = new PipeManager();
PipeManager.Initialize();
}
public void StartCommunicationEndPoint()
{
Console.WriteLine("StartCommunctionEndPointed called");
//PipeManager = new PipeManager();
//PipeManager.Initialize();
//PipeManager.Start();
PipeManager.Start();
}
public void CloseCommunicationEndPoint()
{
PipeManager.Stop();
}
}
}

View File

@@ -0,0 +1,126 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using AppModule.NamedPipes;
using sscs.communication.win;
using sscs.common;
using sscs.verbs;
using sscs.constants;
namespace sscs.communication
{
class WinIPCChannel : IPCChannel
{
// Data
private ServerPipeConnection m_serverPipeConnection;
private WinUserIdentifier userId = null;
//Methods
public WinIPCChannel(ServerPipeConnection serverPipeConnection)
{
m_serverPipeConnection = serverPipeConnection;
}
override internal UserIdentifier GetIPCChannelUserId()
{
CSSSLogger.DbgLog("In WinIPCChannel::GetIPCChannelUserId");
return userId;
}
private WinIPCChannel()
{
CSSSLogger.DbgLog("WinIPCChannel constructor must be called with a serverPipe");
}
~WinIPCChannel()
{
// Console.WriteLine("WinIPCChannel::~~WinIPCChannel");
}
override internal byte[] Read()
{
int localUserIDLow = 0;
int localUserIDHigh = 0;
string sSIDString = "";
byte[] incoming = null;
try
{
incoming = m_serverPipeConnection.ReadBytes();
// get local Userid and SID
m_serverPipeConnection.GetLocalUserID(ref localUserIDLow, ref localUserIDHigh, ref sSIDString);
if (localUserIDLow != 0 || localUserIDHigh !=0)
{
userId = new WinUserIdentifier(localUserIDLow, localUserIDHigh, sSIDString);
}
return incoming;
}
catch(Exception e)
{
return null;
//CSSSLogger.DbgLog("Exception in reading data from client" + e.ToString());
//throw new CommunicationException(e.ToString());
}
}
override internal int Read(byte[] buf)
{
return 0;
}
override internal int Write(byte[] buf)
{
int bytesSent = 0;
try
{
m_serverPipeConnection.WriteBytes(buf);
bytesSent = buf.Length;
}
catch (Exception)
{
}
CSSSLogger.DbgLog("WinIPCChannel::Write - Bytes sent is {0}" +bytesSent);
return bytesSent;
}
override internal void Close()
{
CSSSLogger.DbgLog("WinIPCChannel Closed");
//clientSocket.Close();
m_serverPipeConnection.Close();
}
}
}

View File

@@ -0,0 +1,167 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Threading;
using System.Web;
using System.IO;
using System.Configuration;
using System.Diagnostics;
using AppModule.InterProcessComm;
using AppModule.NamedPipes;
namespace sscs.communication.win {
public class PipeManager : IChannelManager {
public Hashtable Pipes;
private uint NumberPipes = 16;
private uint OutBuffer = 65536; //512;
private uint InBuffer = 65536; //512;
private const int MAX_READ_BYTES = 5000;
private bool _listen = true;
public bool Listen {
get {
return _listen;
}
set {
_listen=value;
}
}
private int numChannels = 0;
private Hashtable _pipes = new Hashtable();
//private Thread MainThread;
private string CASA_RPC_PIPE = "\\\\.\\PIPE\\SS_RPC_PIPE";
private ManualResetEvent Mre;
private const int PIPE_MAX_STUFFED_TIME = 5000;
public object SyncRoot = new object();
public void Initialize() {
Pipes = Hashtable.Synchronized(_pipes);
Mre = new ManualResetEvent(false);
/*
MainThread = new Thread(new ThreadStart(Start));
MainThread.IsBackground = true;
MainThread.Name = "Main Pipe Thread";
MainThread.Start();
*/
Thread.Sleep(1000);
}
public string HandleRequest(string request) {
string returnVal;
//Form1.ActivityRef.AppendText(request + Environment.NewLine);
returnVal = "Response to: " + request;
return returnVal;
}
public void Start() {
try {
while (_listen) {
int[] keys = new int[Pipes.Keys.Count];
Pipes.Keys.CopyTo(keys,0);
foreach (int key in keys) {
ServerNamedPipe serverPipe = (ServerNamedPipe)Pipes[key];
if (serverPipe != null && DateTime.Now.Subtract(serverPipe.LastAction).Milliseconds > PIPE_MAX_STUFFED_TIME && serverPipe.PipeConnection.GetState() != InterProcessConnectionState.WaitingForClient) {
serverPipe.Listen = false;
serverPipe.PipeThread.Abort();
RemoveServerChannel(serverPipe.PipeConnection.NativeHandle);
}
}
if (numChannels <= NumberPipes) {
ServerNamedPipe pipe = new ServerNamedPipe(CASA_RPC_PIPE, OutBuffer, InBuffer, MAX_READ_BYTES);
try {
pipe.Connect();
pipe.LastAction = DateTime.Now;
System.Threading.Interlocked.Increment(ref numChannels);
pipe.Start();
Pipes.Add(pipe.PipeConnection.NativeHandle, pipe);
}
catch (InterProcessIOException) {
RemoveServerChannel(pipe.PipeConnection.NativeHandle);
pipe.Dispose();
}
}
else {
Mre.Reset();
Mre.WaitOne(1000, false);
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception starting server: "+e.ToString());
// Log exception
}
}
public void Stop() {
_listen = false;
Mre.Set();
try {
int[] keys = new int[Pipes.Keys.Count];
Pipes.Keys.CopyTo(keys,0);
foreach (int key in keys) {
((ServerNamedPipe)Pipes[key]).Listen = false;
}
int i = numChannels * 3;
for (int j = 0; j < i; j++) {
StopServerPipe();
}
Pipes.Clear();
Mre.Close();
Mre = null;
}
catch {
// Log exception
}
}
public void WakeUp() {
if (Mre != null) {
Mre.Set();
}
}
private void StopServerPipe() {
try {
ClientPipeConnection pipe = new ClientPipeConnection(CASA_RPC_PIPE);
if (pipe.TryConnect()) {
pipe.Close();
}
} catch {
// Log exception
}
}
public void RemoveServerChannel(object param) {
int handle = (int)param;
System.Threading.Interlocked.Decrement(ref numChannels);
Pipes.Remove(handle);
this.WakeUp();
}
}
}

View File

@@ -0,0 +1,127 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Threading;
using System.IO;
using AppModule.InterProcessComm;
using AppModule.NamedPipes;
namespace sscs.communication.win {
public sealed class ServerNamedPipe : IDisposable {
internal Thread PipeThread;
internal ServerPipeConnection PipeConnection;
internal bool Listen = true;
internal DateTime LastAction;
private bool disposed = false;
private void PipeListener() {
CheckIfDisposed();
try {
Listen = true;
while (Listen) {
LastAction = DateTime.Now;
// Service Client (new code)
IPCChannel ipcChannel = IPCChannel.Create(PipeConnection);
AppHandler appHandler = new AppHandler(ipcChannel);
try
{
int retVal = appHandler.ServiceApp();
}
catch(Exception)
{
ipcChannel.Close();
}
LastAction = DateTime.Now;
PipeConnection.Disconnect();
if (Listen) {
Connect();
}
WinCommunication.PipeManager.WakeUp();
}
}
catch (System.Threading.ThreadAbortException) { }
catch (System.Threading.ThreadStateException) { }
catch (Exception) {
// Log exception
}
finally {
this.Close();
}
}
internal void Connect() {
CheckIfDisposed();
PipeConnection.Connect();
}
internal void Close() {
CheckIfDisposed();
this.Listen = false;
WinCommunication.PipeManager.RemoveServerChannel(this.PipeConnection.NativeHandle);
this.Dispose();
}
internal void Start() {
CheckIfDisposed();
PipeThread.Start();
}
private void CheckIfDisposed() {
if(this.disposed) {
throw new ObjectDisposedException("ServerNamedPipe");
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
if(!this.disposed) {
PipeConnection.Dispose();
if (PipeThread != null) {
try {
PipeThread.Abort();
}
catch (System.Threading.ThreadAbortException) { }
catch (System.Threading.ThreadStateException) { }
catch (Exception) {
// Log exception
}
}
}
disposed = true;
}
~ServerNamedPipe() {
Dispose(false);
}
internal ServerNamedPipe(string name, uint outBuffer, uint inBuffer, int maxReadBytes) {
PipeConnection = new ServerPipeConnection(name, outBuffer, inBuffer, maxReadBytes, false);
PipeThread = new Thread(new ThreadStart(PipeListener));
PipeThread.IsBackground = true;
PipeThread.Name = "Pipe Thread " + this.PipeConnection.NativeHandle.ToString();
LastAction = DateTime.Now;
}
}
}

125
micasad/init/AppHandler.cs Normal file
View File

@@ -0,0 +1,125 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using sscs.communication;
using sscs.common;
using sscs.verbs;
using sscs.constants;
class AppHandler
{
//Data
private IPCChannel clientChannel;
//Methods
internal AppHandler(IPCChannel ipcChannel)
{
clientChannel = ipcChannel;
CSSSLogger.ExecutionTrace(this);
}
~AppHandler()
{
CSSSLogger.ExecutionTrace(this);
}
/* Starts servicing the application. This is called as soon
* as a new client connection is established.
*/
internal int ServiceApp()
{
SSVerb verb = null;
CSSSLogger.ExecutionTrace(this);
while(true)
{
byte[] buf = null;
try
{
buf = clientChannel.Read();
if( null == buf )
{
return RetCodes.SUCCESS;
}
RequestParser reqParser = new RequestParser();
verb = reqParser.ParseRequest(buf);
CSSSLogger.logbreak();
CSSSLogger.DbgLog("SSCS going to sevice a :: ** " + verb.GetVerbName() + " **");
UserIdentifier userId = clientChannel.GetIPCChannelUserId();
if(null == userId)
{
CSSSLogger.log(ConstStrings.DEBUG, "In " + CSSSLogger.GetExecutionPath(this) + " a null user is obtained.");
return RetCodes.FAILURE;
}
buf = verb.ProcessRequest(userId);
if ( buf != null)
{
int retVal = clientChannel.Write(buf);
if(retVal < 0)
{
CSSSLogger.DbgLog("Write failed");
return RetCodes.FAILURE;
}
}
else
{
//There must always be something written back to client.
return RetCodes.FAILURE;
}
}
catch(CommunicationException e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
catch(FormatException e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw e;
}
/* TBD define verb specific heirarchy of exceptions catch
* (Some processing problem)
*/
finally
{
CSSSLogger.DbgLog("SSCS finished processing a SS Verb :: ** " + verb.GetVerbName() + " **");
CSSSLogger.logbreak();
}
}
}
}

139
micasad/init/CredMgr.cs Normal file
View File

@@ -0,0 +1,139 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Diagnostics;
namespace sscs.init
{
/// <summary>
/// Summary description for RegCredMgr.
/// </summary>
public class CredMgr
{
public CredMgr()
{
}
public static void Install()
{
System.Diagnostics.Debug.WriteLine("CASA: attempting to register lcredmgr");
string sExePath = GetRegSvrPath();
if (sExePath != null)
{
string sCredMgrPath = GetCredMgrPath();
if (sCredMgrPath != null)
{
RunProcess(sExePath, "/i /n /s " + "\"" + sCredMgrPath + "\"");
}
}
}
public static void Uninstall()
{
System.Diagnostics.Debug.WriteLine("CASA: attempting to unregister lcredmgr");
string sExePath = GetRegSvrPath();
if (sExePath != null)
{
string sCredMgrPath = GetCredMgrPath();
if (sCredMgrPath != null)
{
RunProcess(sExePath, "/u /s " + "\"" + sCredMgrPath + "\"");
}
}
}
private static void RunProcess(string sProcess, string sArgs)
{
if (sProcess != null)
{
try
{
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(sProcess);
if (sArgs != null)
myProcessStartInfo.Arguments = sArgs;
myProcessStartInfo.UseShellExecute = false;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
myProcess.WaitForExit();
System.Diagnostics.Debug.WriteLine("Completed " + myProcess.ExitCode.ToString());
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
}
}
private static string GetRegSvrPath()
{
string sPath = Environment.GetEnvironmentVariable("SystemRoot");
if (sPath != null)
{
// look for regsvr32.exe
if (File.Exists(sPath + "\\system32\\regsvr32.exe"))
{
return (sPath + "\\system32\\regsvr32.exe");
}
else
{
System.Diagnostics.Debug.WriteLine("Did not find regsvr32.exe");
}
}
else
{
System.Diagnostics.Debug.WriteLine("Did not find System path");
}
return null;
}
private static string GetCredMgrPath()
{
string sPath = Environment.GetEnvironmentVariable("ProgramFiles");
if (sPath != null)
{
// look for regsvr32.exe
if (File.Exists(sPath + "\\Novell\\CASA\\bin\\lcredmgr.dll"))
{
return (sPath + "\\Novell\\CASA\\bin\\lcredmgr.dll");
}
else
{
System.Diagnostics.Debug.WriteLine("Did not find lcredmgr.dll");
}
}
else
{
System.Diagnostics.Debug.WriteLine("Did not find path to [ProgramFiles]");
}
return null;
}
}
}

227
micasad/init/Main.cs Normal file
View File

@@ -0,0 +1,227 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Diagnostics;
using sscs.communication;
using sscs.constants;
using sscs.common;
class SecretStoreClientService
{
private static Communication server = null;
private static Thread listeningThread = null;
public static void Main(string[] args)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
/* If getting a lock fails, just exit.
*/
if(!AcquireLock())
{
Console.WriteLine("Another instance of micasad is already running");
Mono.Unix.Native.Syscall.exit(-1);
}
RegisterSignals();
Mono.Unix.Native.Syscall.umask( Mono.Unix.Native.FilePermissions.S_IRGRP |
Mono.Unix.Native.FilePermissions.S_IWGRP |
Mono.Unix.Native.FilePermissions.S_IROTH |
Mono.Unix.Native.FilePermissions.S_IWOTH);
CSSSLogger.DbgLog("Client Side SecretStore Service has started.");
server = CommunicationFactory.CreateCommunicationEndPoint();
listeningThread = new Thread(new ThreadStart(StartServer));
listeningThread.Start();
listeningThread.Join();
}
catch(Exception e)
{
Terminate();
}
}
/* The thread which listens and spawns threads on every accept
* starts its execution from this method.
*/
private static void StartServer()
{
try
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
server.StartCommunicationEndPoint();
}
catch(ThreadAbortException exp)
{
CSSSLogger.DbgLog("Listening thread of miCASAd is going down.");
CSSSLogger.ExpLog(exp.ToString());
}
catch(Exception exp)
{
CSSSLogger.ExpLog(exp.ToString());
}
CSSSLogger.DbgLog("Listening thread of miCASAd is going down.");
}
/* This ensures that there is only one instance of
* SSCS at any point.
*/
private static bool AcquireLock()
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
int platform = (int)Environment.OSVersion.Platform;
if( (platform == 128) || (platform == 4) )
{
if(File.Exists(ConstStrings.SSCS_LINUX_PIDFILE))
{
if(CheckIfMiCASAdIsRunning())
{
CSSSLogger.DbgLog("Acquiring lock failed. Terminating miCASAd.");
return false;
}
else
{
File.Delete(ConstStrings.SSCS_LINUX_PIDFILE);
CreatePidFile();
return true;
}
}
else
{
CreatePidFile();
return true;
}
}
else
return false;
}
private static void RegisterSignals()
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
if(( (int)Environment.OSVersion.Platform) == 128)
{
//SIGTERM
Mono.Unix.Native.Stdlib.signal(Mono.Unix.Native.Signum.SIGTERM, new Mono.Unix.Native.SignalHandler(Terminate));
//SIGINT
Mono.Unix.Native.Stdlib.signal(Mono.Unix.Native.Signum.SIGINT, new Mono.Unix.Native.SignalHandler(Terminate));
//SIGHUP
Mono.Unix.Native.Stdlib.signal(Mono.Unix.Native.Signum.SIGHUP, new Mono.Unix.Native.SignalHandler(Terminate));
}
}
private static void Terminate(int sigNum)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Terminate();
}
private static void Terminate()
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
CSSSLogger.DbgLog("Client Side SecretStore Service is now exiting.");
if( listeningThread != null )
{
listeningThread.Abort("Aborting listening thread");
}
int platform = (int)Environment.OSVersion.Platform;
if( (platform == 128) || (platform == 4) )
{
if( File.Exists(ConstStrings.SSCS_LINUX_PIDFILE) )
{
File.Delete(ConstStrings.SSCS_LINUX_PIDFILE);
}
Mono.Unix.Native.Syscall.exit(0);
}
}
private static void CreatePidFile()
{
int pid = Mono.Unix.Native.Syscall.getpid();
string pidStr = String.Format("{0}",pid);
FileInfo fInfo = new FileInfo(ConstStrings.SSCS_LINUX_PIDFILE);
FileStream fs = fInfo.Open(System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter w = new StreamWriter(fs);
w.Write(pidStr);
w.Flush();
fs.Close();
}
private static bool CheckIfMiCASAdIsRunning()
{
try
{
StreamReader sr = new StreamReader(ConstStrings.SSCS_LINUX_PIDFILE);
string line = sr.ReadLine();
if( line == null )
{
sr.Close();
return false;
}
string procPath = "/proc/"+ line + "/cmdline";
/* If the file procPath itself does not exist,
* then another instance is surely not running.
*/
if( !File.Exists(procPath) )
{
return false;
}
/* There is a possibility that the pid stored in
* the pidfile has been reassigned to another process.
* So, if procPath exists, check if the process is
* micasad.exe.
*/
StreamReader procReader = new StreamReader(procPath);
string cmdline = procReader.ReadLine();
/*
string assemblyName = (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Assembly.FullName + ".exe\0";
*/
string assemblyName = "micasad.exe\0";
if(cmdline.EndsWith(assemblyName))
{
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
return false;
}
}
}

View File

@@ -0,0 +1,150 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
namespace sscs.init
{
/// <summary>
/// Summary description for ProjectInstaller.
/// </summary>
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private static string SERVICE_DESCRIPTION = "Novell Identity Store is used by CASA (Common Authentication Service Adapter) "
+ "to encypt and store credentials entered by users. These credentials can be used to authenticate to additional network services";
private static string SERVICE_GROUP = "Base";
public ProjectInstaller()
{
// This call is required by the Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
//
// serviceInstaller1
//
this.serviceInstaller1.DisplayName = WinSecretStoreClientService.sServiceName;
this.serviceInstaller1.ServiceName = WinSecretStoreClientService.sServiceName;
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
#endregion
private void serviceInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
}
private void serviceProcessInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
}
public override void Install(IDictionary stateServer)
{
Microsoft.Win32.RegistryKey system,
currentControlSet,
services,
service,
config;
try
{
//Let the project installer do its job
base.Install(stateServer);
//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");
//Open the key for your service, and allow writing
service = services.OpenSubKey(this.serviceInstaller1.ServiceName, true);
//Add service's description as a REG_SZ value named "Description"
service.SetValue("Description", SERVICE_DESCRIPTION);
service.SetValue("Group", SERVICE_GROUP);
}
catch(Exception e)
{
Console.WriteLine("An exception was thrown during service installation:\n" + e.ToString());
}
}
}
}

View File

@@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="serviceProcessInstaller1.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="serviceProcessInstaller1.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="serviceProcessInstaller1.Location" type="System.Drawing.Point, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</data>
<data name="serviceInstaller1.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="serviceInstaller1.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="serviceInstaller1.Location" type="System.Drawing.Point, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>187, 17</value>
</data>
<data name="$this.Name">
<value>ProjectInstaller</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
</root>

View File

@@ -0,0 +1,296 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install ;
using sscs.communication;
using sscs.constants;
using sscs.common;
namespace sscs.init
{
public class WinSecretStoreClientService : System.ServiceProcess.ServiceBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private static Communication server;
private static Thread listeningThread;
public static string sServiceName = "Novell Identity Store";
public WinSecretStoreClientService()
{
// This call is required by the Windows.Forms Component Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// SecretStoreClientService
//
this.CanHandlePowerEvent = true;
this.ServiceName = "SecretStoreService";
}
#endregion
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
static void Main(string[] args)
{
string opt = null ;
if ( args.Length > 0)
{
opt = args [0];
}
if (opt != null && opt.ToLower () == "/install")
{
stopService();
uninstallService();
installService();
startService();
CredMgr.Install();
return;
}
else if (opt != null && opt.ToLower () == "/uninstall")
{
stopService();
uninstallService();
CredMgr.Uninstall();
return;
}
if (opt != null && opt.ToLower() == "/standalone")
{
MainInternal(args);
}
else
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinSecretStoreClientService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
private static void installService()
{
TransactedInstaller ti = new TransactedInstaller ();
ProjectInstaller mi = new ProjectInstaller ();
ti.Installers.Add (mi);
String path = String.Format ("/assemblypath={0}",
System.Reflection.Assembly.GetExecutingAssembly ().Location);
String[] cmdline = {path};
InstallContext ctx = new InstallContext ("", cmdline );
ti.Context = ctx;
try
{
ti.Install ( new Hashtable ());
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
}
private static void uninstallService()
{
// kill all running versions of CASA manager
Process[] proc = System.Diagnostics.Process.GetProcessesByName("CASAManager");
for (int i = 0; i < proc.Length; i++)
{
try
{
proc[i].Kill();
}
catch { }
}
TransactedInstaller ti = new TransactedInstaller ();
ProjectInstaller mi = new ProjectInstaller ();
ti.Installers.Add (mi);
String path = String.Format ("/assemblypath={0}",
System.Reflection.Assembly.GetExecutingAssembly ().Location);
String[] cmdline = {path};
InstallContext ctx = new InstallContext ("", cmdline );
ti.Context = ctx;
try
{
ti.Uninstall ( null );
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
}
private static void stopService()
{
ServiceController[] services=ServiceController.GetServices();
foreach(ServiceController x in services)
{
if(x.DisplayName.Equals(sServiceName))
{
if (x.Status==System.ServiceProcess.ServiceControllerStatus.Running)
{
x.Stop();
}
}
}
}
private static void startService()
{
ServiceController[] services=ServiceController.GetServices();
// Iterating each service to check that if a service named
// 'Novell Identity Store' is found then check that its status whether
// it is running or stopped. If found running then it will
// stop that service; else it starts that service
foreach(ServiceController x in services)
{
if(x.DisplayName.Equals(sServiceName))
{
CSSSLogger.DbgLog("Checking service: " + x.DisplayName);
if (x.Status==System.ServiceProcess.ServiceControllerStatus.Stopped)
{
x.Start();
}
}
}
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
///
protected override void OnStart(string[] args)
{
AcquireLock();
server = CommunicationFactory.CreateCommunicationEndPoint();
listeningThread = new Thread(new ThreadStart(StartServer));
listeningThread.Start();
//listeningThread.Join();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
listeningThread.Abort();
}
/* The thread which listens and spawns threads on every accept
* starts its execution from this method.
*/
private static void StartServer()
{
server.StartCommunicationEndPoint();
}
/* This ensures that there is only one instance of
* SSCS at any point.
*/
private static int AcquireLock()
{
return RetCodes.SUCCESS;
}
private static void MainInternal(string[] args)
{
CSSSLogger.ExecutionTrace(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
int retVal = AcquireLock();
if( retVal != RetCodes.SUCCESS )
{
CSSSLogger.DbgLog("Acquiring lock failed. Terminating CSSS.");
// Terminate();
}
// RegisterAtExit();
CSSSLogger.DbgLog("Client Side SecretStore Service has started.");
server = CommunicationFactory.CreateCommunicationEndPoint();
listeningThread = new Thread(new ThreadStart(StartServer));
listeningThread.Start();
listeningThread.Join();
}
catch(Exception e)
{
// Terminate();
}
}
/* The thread which listens and spawns threads on every accept
* starts its execution from this method.
*/
}
}

View File

@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.Name">
<value>SecretStoreClientService</value>
</data>
</root>

View File

@@ -0,0 +1,80 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("Novell.CASA.Common.dll")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Novell, Inc")]
[assembly: AssemblyProduct("CASA")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.6.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

111
micasad/lib/Makefile.am Normal file
View File

@@ -0,0 +1,111 @@
#######################################################################
#
# Copyright (C) 2006 Novell, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#######################################################################
if DEBUG
TARGET_CFG = Debug
CFLAGS += -v -w
#CS_EXTRA_FLAGS = $(CSCFLAGS_DEBUG)
else
TARGET_CFG = Release
endif
SUBDIRS =
DIST_SUBDIRS = common communication
EXTRA_DIST = $(CSFILES)
CASAROOT = ../..
CASALIBDIR = $(CASAROOT)/$(LIB)
# handle Mono secondary dependencies
export MONO_PATH := $(MONO_PATH)
PLATFORMINDEPENDENTSOURCEDIR =
PLATFORMDEPENDENTSOURCEDIR = .
MODULE_NAME =Novell.CASA.Common
MODULE_EXT =dll
CSFILES = $(srcdir)/AssemblyInfo.cs \
$(srcdir)/common/LinkedKeyInfo.cs \
$(srcdir)/common/Utils.cs \
$(srcdir)/common/Ping.cs \
$(srcdir)/common/ResetMasterPassword.cs \
$(srcdir)/common/WrappedObject.cs \
$(srcdir)/common/MiCASAStore.cs \
$(srcdir)/communication/IClientChannel.cs \
$(srcdir)/communication/IPCClientFactory.cs \
$(srcdir)/communication/MiCasaRequestReply.cs \
$(srcdir)/communication/UnixIPCClientChannel.cs
CSFILES_CSC := $(subst /,$(SEP),$(CSFILES))
CS_INCLUDES = -I. -I.. -I$(CASAROOT)/include
CS_FLAGS = /target:"library" /r:Mono.Posix.dll -d:LINUX
CS_RESOURCES =
CS_LIBS =
CS_LIBPATH =
OBJDIR = ./$(TARGET_CFG)/$(LIB)
#OBJS = $(addprefix $(OBJDIR)/, $(CSFILES:%.dll=%.cs))
CUR_DIR := $(shell pwd)
all: $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
#
# Pattern based rules.
#
vpath %.c $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
vpath %.cpp $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
vpath %.cs $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
$(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT): $(OBJDIR) $(CSFILES)
$(CSC) $(CS_FLAGS) $(CS_EXTRA_FLAGS) -out:$@ $(CSFILES_CSC)
cp -f $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT) $(CASALIBDIR)/$(TARGET_CFG)/$(MODULE_NAME).$(MODULE_EXT)
$(OBJDIR):
[ -d $(OBJDIR) ] || mkdir -p $(OBJDIR)
[ -d $(CASALIBDIR) ] || mkdir -p $(CASALIBDIR)
[ -d $(CASALIBDIR)/$(TARGET_CFG) ] || mkdir -p $(CASALIBDIR)/$(TARGET_CFG)
install-exec-local: $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
$(mkinstalldirs) $(DESTDIR)$(libdir)
$(INSTALL_PROGRAM) $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT) $(DESTDIR)$(libdir)/
uninstall-local:
cd $(DESTDIR)$(libdir); rm -f $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
rmdir $(DESTDIR)$(libdir)
#installcheck-local: install
# $(mkinstalldirs) $(DESTDIR)$(libdir)
# $(INSTALL_PROGRAM) $(DESTDIR)$(libdir)
# cd $(DESTDIR)$(libdir); $(MONO)
clean-local:
if [ -d $(TARGET_CFG) ]; then rm -rf $(TARGET_CFG); fi
distclean-local:
maintainer-clean-local:
rm -f Makefile.in

View File

@@ -0,0 +1,155 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.10.3077"
SchemaVersion = "2.0"
ProjectGuid = "{57CD94A2-5B4A-40C3-8189-CB760FB78357}"
>
<Build>
<Settings
ApplicationIcon = ""
AssemblyKeyContainerName = ""
AssemblyName = "Novell.CASA.Common"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "Library"
PreBuildEvent = ""
PostBuildEvent = ""
RootNamespace = "MiCasaLibrary"
RunPostBuildEvent = "OnBuildSuccess"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE;W32"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE; W32"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll"
/>
<Reference
Name = "AppModule.InterProcessComm"
Project = "{E98F1F7E-40B6-44C8-AC66-EC867B141FA1}"
Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
/>
<Reference
Name = "AppModule.NamedPipes"
Project = "{077B53BB-404A-4B2F-BA17-AAE98C5E9C66}"
Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\LinkedKeyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\MiCASAStore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\Ping.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\ResetMasterPassword.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\Utils.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\WrappedObject.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\IClientChannel.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\IPCClientFactory.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\MiCasaRequestReply.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\WinIPCClientChannel.cs"
SubType = "Code"
BuildAction = "Compile"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,48 @@
<VisualStudioProject>
<CSHARP LastOpenVersion = "7.10.3077" >
<Build>
<Settings ReferencePath = "D:\csharp\namedpipe2\AppModule.InterProcessComm\bin\Debug\;D:\csharp\namedpipe2\AppModule.NamedPipes\bin\Debug\;D:\casatest\extern\w32\namedpipes\;D:\casaoutside\extern\w32\namedpipes\;D:\casaAll\trunk\extern\w32\namedpipes\" >
<Config
Name = "Debug"
EnableASPDebugging = "false"
EnableASPXDebugging = "false"
EnableUnmanagedDebugging = "false"
EnableSQLServerDebugging = "false"
RemoteDebugEnabled = "false"
RemoteDebugMachine = ""
StartAction = "Project"
StartArguments = ""
StartPage = ""
StartProgram = ""
StartURL = ""
StartWorkingDirectory = ""
StartWithIE = "true"
/>
<Config
Name = "Release"
EnableASPDebugging = "false"
EnableASPXDebugging = "false"
EnableUnmanagedDebugging = "false"
EnableSQLServerDebugging = "false"
RemoteDebugEnabled = "false"
RemoteDebugMachine = ""
StartAction = "Project"
StartArguments = ""
StartPage = ""
StartProgram = ""
StartURL = ""
StartWorkingDirectory = ""
StartWithIE = "true"
/>
</Settings>
</Build>
<OtherProjectSettings
CopyProjectDestinationFolder = ""
CopyProjectUncPath = ""
CopyProjectOption = "0"
ProjectView = "ShowAllFiles"
ProjectTrust = "0"
/>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,98 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace Novell.CASA.MiCasa.Common
{
/// <summary>
/// Summary description for LinkInfo.
/// </summary>
///
[Serializable]
public class LinkedKeyInfo
{
//private string m_sDestStoreID = null;
//private string m_sDestKeychainID = null;
private string m_sDestSecretID = null;
private string m_sDestKeyID = null;
public LinkedKeyInfo(string sDestSecretID, string sDestKey)
{
if (sDestSecretID != null)
{
if (sDestSecretID.StartsWith("SS_CredSet"))
sDestSecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sDestSecretID.Substring(11)) + '\0';
else
sDestSecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sDestSecretID) + '\0';
}
m_sDestSecretID = sDestSecretID;
m_sDestKeyID = sDestKey;
}
public LinkedKeyInfo(string sDestSecretID, string sDestKey, bool bAlreadyEscaped)
{
if (!bAlreadyEscaped)
{
if (sDestSecretID != null)
{
if (sDestSecretID.StartsWith("SS_CredSet"))
sDestSecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sDestSecretID.Substring(11)) + '\0';
else
sDestSecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sDestSecretID) + '\0';
}
}
m_sDestSecretID = sDestSecretID;
m_sDestKeyID = sDestKey;
}
public string GetLinkID()
{
return m_sDestSecretID + ":" + m_sDestKeyID;
}
public string GetLinkedSecretID()
{
return m_sDestSecretID;
}
public string GetLinkedSecretID(bool bUnescape)
{
if (bUnescape)
{
if (m_sDestSecretID.StartsWith("SS_CredSet"))
return ("SS_CredSet:" + Utils.UnescapeString(m_sDestSecretID.Substring(11)));
else
return Utils.UnescapeString(m_sDestSecretID);
}
return m_sDestSecretID;
}
public string GetLinkedKeyID()
{
return m_sDestKeyID;
}
}
}

View File

@@ -0,0 +1,36 @@
#######################################################################
#
# Copyright (C) 2006 Novell, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#######################################################################
SUBDIRS =
DIST_SUBDIRS =
CFILES =
EXTRA_DIST = $(CSFILES)
.PHONY: package package-clean package-install package-uninstall
package package-clean package-install package-uninstall:
$(MAKE) -C $(TARGET_OS) $@
maintainer-clean-local:
rm -f Makefile.in

View File

@@ -0,0 +1,52 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using Novell.CASA.MiCasa.Common;
using Novell.CASA.MiCasa.Communication;
namespace Novell.CASA.MiCasa.Common
{
/// <summary>
/// Summary description for MiCASAStore.
/// </summary>
public class MiCASAStore
{
public MiCASAStore()
{
//
// TODO: Add constructor logic here
//
}
public static bool IsLocked()
{
Object o = MiCasaRequestReply.Send(MiCasaRequestReply.VERB_GET_STORE_STATUS);
if ((o != null) && ((System.Int32)o == 2))
return true;
else
return false;
}
}
}

View File

@@ -0,0 +1,46 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace Novell.CASA.MiCasa.Common
{
/// <summary>
/// Summary description for Ping.
/// </summary>
///
[Serializable]
public class Ping
{
public Ping()
{
//
// TODO: Add constructor logic here
//
}
public string clientmessage;
public string servermessage;
}
}

View File

@@ -0,0 +1,44 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace Novell.CASA.MiCasa.Common
{
/// <summary>
/// Summary description for ResetMasterPassword.
/// </summary>
///
[Serializable]
public class ResetMasterPassword
{
public string m_currentPassword;
public string m_newPassword;
public int rcode = 0;
public ResetMasterPassword(string currentPassword, string newPassword)
{
m_currentPassword = currentPassword;
m_newPassword = newPassword;
}
}
}

View File

@@ -0,0 +1,83 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
// using System.Collections.Generic;
using System.Text;
namespace Novell.CASA.MiCasa.Common
{
class Utils
{
public static string EscapeReservedChars(string origString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < origString.Length; i++)
{
switch (origString[i])
{
case ':':
{
sb.Append("\\");
break;
}
case '\\':
{
sb.Append("\\");
break;
}
case '=':
{
sb.Append("\\");
break;
}
}
sb.Append(origString[i]);
}
return sb.ToString();
}
public static string UnescapeString(string sOrig)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sOrig.Length; i++)
{
if (sOrig[i].Equals('\\'))
{
if (i + 1 < sOrig.Length)
{
if (sOrig[i + 1].Equals(':')
|| sOrig[i + 1].Equals('\\')
|| sOrig[i + 1].Equals('='))
{
i++;
}
}
}
sb.Append(sOrig[i]);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,122 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
namespace Novell.CASA.MiCasa.Common
{
/// <summary>
/// Summary description for MessageObject.
/// </summary>
///
[Serializable]
public class WrappedObject
{
public static string DEFAULT_KEYCHAIN_ID = "SSCS_SESSION_KEY_CHAIN_ID\0";
private int m_verb = 0;
private string m_KeychainID = null;
private string m_SecretID = null;
private string m_KeyID = null;
private object m_object;
private int m_rcode = 0;
private string m_errorMsg;
public WrappedObject(int rcode, string errorMsg)
{
m_rcode = rcode;
m_errorMsg = errorMsg;
}
public WrappedObject(int verb, string sKeychainID, string sSecretID, string sKeyID, object theObject)
{
m_verb = verb;
if (sKeychainID != null)
m_KeychainID = sKeychainID + '\0';
else
m_KeychainID = DEFAULT_KEYCHAIN_ID;
if (sSecretID != null)
{
if (sSecretID.StartsWith("SS_CredSet"))
m_SecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sSecretID.Substring(11)) + '\0';
else
m_SecretID = "SS_CredSet:" + Utils.EscapeReservedChars(sSecretID) + '\0';
}
if (sKeyID != null)
m_KeyID = Utils.EscapeReservedChars(sKeyID); // + '\0';
// serialize the object
m_object = theObject;
}
public string GetKeyID()
{
return m_KeyID;
}
public string GetSecretID()
{
return m_SecretID;
}
public string GetKeychainID()
{
return m_KeychainID;
}
public object GetObject()
{
return m_object;
}
public void SetObject(object theobject)
{
m_object = theobject;
}
public int GetAction()
{
return m_verb;
}
public void SetError(int rcode, string message)
{
m_rcode = rcode;
m_errorMsg = message;
}
public int GetReturnCode()
{
return m_rcode;
}
public string GetReturnMessage()
{
return m_errorMsg;
}
}
}

View File

@@ -0,0 +1,40 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Net;
using System.Net.Sockets;
//using sscs.communication.win.NamedPipes;
namespace Novell.CASA.MiCasa.Communication
{
public interface ClientChannel
{
void Open();
int Read(byte[] buf);
byte[] Read();
int Write(byte[] buf);
void Close();
}
}

View File

@@ -0,0 +1,50 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
namespace Novell.CASA.MiCasa.Communication
{
/// <summary>
/// Summary description for IPCClientFactory.
/// </summary>
public class IPCClientFactory
{
private IPCClientFactory()
{
}
public static ClientChannel CreateClientConnection()
{
#if LINUX
return( new UnixIPCClientChannel());
#endif
#if W32
return (new WinIPCClientChannel());
#endif
}
}
}

View File

@@ -0,0 +1,36 @@
#######################################################################
#
# Copyright (C) 2006 Novell, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#######################################################################
SUBDIRS =
DIST_SUBDIRS =
CFILES =
EXTRA_DIST = $(CSFILES)
.PHONY: package package-clean package-install package-uninstall
package package-clean package-install package-uninstall:
$(MAKE) -C $(TARGET_OS) $@
maintainer-clean-local:
rm -f Makefile.in

View File

@@ -0,0 +1,185 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Novell.CASA.MiCasa.Common;
namespace Novell.CASA.MiCasa.Communication
{
/// <summary>
/// Summary description for MiCasaRequestReply.
/// </summary>
public class MiCasaRequestReply
{
//public const int VERB_GET_SECRET = 1;
//public const int VERB_SET_SECRET = 2;
//public const int VERB_GET_KEYCHAIN = 3;
//public const int VERB_GET_STORE = 4;
//public const int VERB_SET_KEYVALUE = 5;
//public const int VERB_GET_KEYVALUE = 6;
public const int VERB_SET_LINKED_KEY = 7;
public const int VERB_GET_LINKED_KEYS = 8;
public const int VERB_REMOVE_LINKED_KEY = 9;
public const int VERB_WRITE_KEY = 10;
public const int VERB_REMOVE_ALL_SECRETS = 11;
public const int VERB_LOCK_STORE = 12;
public const int VERB_UNLOCK_STORE = 13;
public const int VERB_GET_STORE_STATUS = 14;
public const int VERB_REMOVE_KEY = 15;
public const int VERB_READ_KEY = 16;
public const int VERB_GET_KEY_LIST = 17;
public const int VERB_RESET_MASTER_PASSWORD = 18;
public const int VERB_GET_SECRETIDS = 19;
public const int VERB_VALIDATE_DESKTOP_PWD = 20;
public const int VERB_DUMP_LINKED_KEYS = 96;
public const int VERB_CREATE_TEST_SECRETS = 97;
public const int VERB_REMOVE_TEST_SECRETS = 98;
public const int VERB_PING_MICASAD = 99;
public MiCasaRequestReply()
{
//
// TODO: Add constructor logic here
//
}
public static object Send(int verb)
{
return Send(verb, null, null, null, null);
}
public static object Send(int verb, object wo)
{
return Send(verb, null, null, null, wo);
}
public static object Send(int verb,
string sKeyChainID,
string sSecretID,
string sKeyID,
object theObject)
{
// Lengths of message fields
int MSGID_LEN = 2;
int MSG_LEN = 4;
WrappedObject request;
WrappedObject reply = null;
// open a client connection
//IInterProcessConnection clientConnection = null;
ClientChannel ipcChannel = IPCClientFactory.CreateClientConnection();
ipcChannel.Open();
try
{
// contruct and serialize the Message Object
request = new WrappedObject(verb, sKeyChainID, sSecretID, sKeyID, theObject);
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, request);
ms.Flush();
ms.Position = 0;
byte[] rawBytes = new byte[2+4+ms.Length];
byte[] t = new byte[10];
// set message id
int destIndex = 0;
ushort msgId = 20;
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,rawBytes,destIndex,MSGID_LEN);
destIndex += MSGID_LEN;
// set the object length
//Poorna
int msgLen = 2+4+(int)ms.Length;
// int msgLen = (int)ms.Length;
t = BitConverter.GetBytes(msgLen);
// t = BitConverter.GetBytes(ms.Length);
Array.Copy(t,0,rawBytes,destIndex,MSG_LEN);
destIndex += MSG_LEN;
// copy in the object
Array.Copy(ms.GetBuffer(), 0, rawBytes, destIndex, ms.Length);
//clientConnection = new ClientPipeConnection("MyPipe", ".");
//clientConnection = new ClientPipeConnection(XTIER_RPC_PIPE, ".");
//clientConnection.Connect();
// write the bytes
//clientConnection.WriteBytes(rawBytes);
ipcChannel.Write(rawBytes);
// read the bytes
//byte[] returnBuffer = clientConnection.ReadBytes();
byte[] returnBuffer = ipcChannel.Read();
if (returnBuffer != null)
{
// deserialize MessageObject
uint iMsgLen = BitConverter.ToUInt32(returnBuffer,0);
ms = new MemoryStream(returnBuffer, 4, (int)iMsgLen);
ms.Position = 0;
reply = (WrappedObject)formatter.Deserialize(ms);
if (reply.GetReturnCode() != 0)
{
ipcChannel.Close();
throw new Exception(reply.GetReturnCode().ToString());
}
}
// close the connection
//clientConnection.Close();
ipcChannel.Close();
}
catch (Exception e1)
{
//Console.WriteLine(e1.ToString());
//clientConnection.Dispose();
//throw new Exception(e1.ToString());
}
if (reply != null)
return reply.GetObject();
else
return null;
}
}
}

View File

@@ -0,0 +1,178 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
using Mono.Unix;
using System.Text;
namespace Novell.CASA.MiCasa.Communication
{
/// <summary>
/// Summary description for UnixIPCClientChannel.
/// </summary>
public class UnixIPCClientChannel : ClientChannel
{
private Socket mSocket = null;
private string socketFileName = "/tmp/.novellCASA";
private EndPoint sockEndPoint;
public UnixIPCClientChannel()
{
}
public void Open()
{
mSocket = new Socket( AddressFamily.Unix,
SocketType.Stream,
ProtocolType.IP );
if (mSocket == null)
{
throw new Exception("could not get socket");
}
sockEndPoint = new UnixEndPoint(socketFileName);
UnixFileSystemInfo sockFileInfo = new UnixFileInfo(socketFileName);
UnixUserInfo sockFileOwner = sockFileInfo.OwnerUser;
// root is the owner of the file "/tmp/.novellCASA"
if (sockFileOwner.UserId == 0)
{
mSocket.Connect(sockEndPoint);
}
else
{
throw new Exception("not a valid miCASA service");
}
}
public int Read(byte[] buf)
{
buf = Read();
if (buf != null)
{
//Console.WriteLine("Bytes read = " + buf.Length);
return buf.Length;
}
else
return 0;
}
public byte[] Read()
{
byte[] returnBuffer = null;
int bytesRecvd = 0;
try
{
/* We need to read 'msgLen' to know how many bytes to
* allocate.
*/
byte[] msgIdBytes = new byte[2];
bytesRecvd = mSocket.Receive(msgIdBytes);
if( 0 == bytesRecvd )
{
return null;
}
byte[] msgLenBytes = new byte[4];
bytesRecvd = mSocket.Receive(msgLenBytes);
if( 0 == bytesRecvd )
{
return null;
}
uint msgLen = BitConverter.ToUInt32(msgLenBytes,0);
if( msgLen > 6 )
{
System.Text.Encoding encoding = System.Text.Encoding.ASCII;
byte[] buf = null;
int bytesAvailable;
int totalBytes = 0;
int msgLencount = 0;
string bufstring = null;
byte[] temp = null;
while(totalBytes<(msgLen-6))
{
bytesAvailable = mSocket.Available;
if( 0 == bytesAvailable)
{
break;
}
buf = new byte[bytesAvailable];
bytesRecvd = mSocket.Receive (buf);
bufstring = bufstring + encoding.GetString(buf); //keep buffering in a string
totalBytes = totalBytes + bytesAvailable;
}
if(totalBytes==0)
return null;
byte[] finalbuf = encoding.GetBytes(bufstring);//finally, convert the string to a byte array of size 'totalBytes'
int returnBufferLen = msgIdBytes.Length+msgLenBytes.Length+totalBytes;
returnBuffer = new byte[returnBufferLen];
Array.Copy(msgIdBytes,returnBuffer,2);
Array.Copy(msgLenBytes,0,returnBuffer,2,4);
Array.Copy(finalbuf,0,returnBuffer,6,finalbuf.Length);
return returnBuffer;
}
else
{
returnBuffer = new byte[6];
Array.Copy(msgIdBytes,returnBuffer,2);
Array.Copy(msgLenBytes,0,returnBuffer,2,4);
return returnBuffer;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
}
public int Write(byte[] buf)
{
try
{
mSocket.Send(buf);
//Console.WriteLine("Bytes written = " + buf.Length);
return buf.Length;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return 0;
}
}
public void Close()
{
mSocket.Close();
}
}
}

View File

@@ -0,0 +1,103 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using AppModule.InterProcessComm;
using AppModule.NamedPipes;
namespace Novell.CASA.MiCasa.Communication
{
/// <summary>
/// Summary description for WinIPCClientChannel.
/// </summary>
public class WinIPCClientChannel : ClientChannel
{
private static IInterProcessConnection clientConnection = null;
private static string XTIER_RPC_PIPE = "SS_RPC_PIPE";
public WinIPCClientChannel()
{
}
public void Open()
{
if (clientConnection == null)
{
clientConnection = new ClientPipeConnection(XTIER_RPC_PIPE, ".");
clientConnection.Connect();
}
}
public int Read(byte[] buf)
{
buf = Read();
if (buf != null)
return 0;
else
return -1;
}
public byte[] Read()
{
byte[] returnBuffer;
try
{
returnBuffer = clientConnection.ReadBytes();
return returnBuffer;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
}
public int Write(byte[] buf)
{
try
{
clientConnection.WriteBytes(buf);
return 0;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return -1;
}
}
public void Close()
{
//clientConnection.Close();
//clientConnection.Dispose();
}
}
}

13
micasad/lib/objs.lux Normal file
View File

@@ -0,0 +1,13 @@
OBJS=\
AssemblyInfo \
common/Utils \
common/LinkedKeyInfo \
common/Ping \
common/ResetMasterPassword \
common/WrappedObject \
common/MiCASAStore \
communication/IClientChannel \
communication/IPCClientFactory \
communication/MiCasaRequestReply \
communication/UnixIPCClientChannel

13
micasad/lib/src.lux Normal file
View File

@@ -0,0 +1,13 @@
SRC=\
AssemblyInfo.cs \
common/Utils.cs \
common/LinkedKeyInfo.cs \
common/Ping.cs \
common/ResetMasterPassword.cs \
common/WrappedObject.cs \
common/MiCASAStore.cs \
communication/IClientChannel.cs \
communication/IPCClientFactory.cs \
communication/MiCasaRequestReply.cs \
communication/UnixIPCClientChannel.cs

731
micasad/lss/CASACrypto.cs Normal file
View File

@@ -0,0 +1,731 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
#if LINUX
using Mono.Unix;
#endif
using sscs.common;
using sscs.constants;
namespace sscs.crypto
{
public class CASACrypto
{
private const int SALTSIZE = 64;
private const int ITERATION_COUNT = 1000;
private const int HASH_SIZE = 32;
internal static byte[] Generate16ByteKeyFromString(string sTheString, string sFilepath, bool bUseOldMethod)
{
byte[] baKey = new byte[16]; //return value
try
{
Rfc2898DeriveBytes pkcs5 = new Rfc2898DeriveBytes(sTheString, SALTSIZE, ITERATION_COUNT, bUseOldMethod);
baKey = pkcs5.GetBytes(16);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Key generation failed");
baKey = null;
}
return baKey;
}
internal static bool StoreKeySetUsingMasterPasscode(byte[] key,
byte[] IV, byte[] baMasterPasscode, string fileName)
{
bool bRet = false;
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor;
encryptor = myRijndael.CreateEncryptor(baMasterPasscode, GenerateAndSaveIV(fileName, myRijndael));
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(key);
fsEncrypt.Write(hash,0,hash.Length);
fsEncrypt.Flush();
csEncrypt = new CryptoStream(fsEncrypt, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(key, 0, key.Length);
csEncrypt.FlushFinalBlock();
bRet = true;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to store the generated key");
bRet = false;
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
return bRet;
}
internal static byte[] GetKeySetFromFile(byte[] baMasterPasscode,
string fileName )
{
byte[] baSavedKey = null;
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
try
{
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if(!File.Exists(fileName))
#endif
{
return null;
}
/* Get a decryptor that uses the same key and IV
* as the encryptor.
*/
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(baMasterPasscode, RetrieveIV(fileName, baMasterPasscode));
//Now decrypt
fsDecrypt = new FileStream(fileName, FileMode.Open);
byte[] storedHash = new byte[32];
fsDecrypt.Read(storedHash,0,storedHash.Length);
csDecrypt = new CryptoStream(fsDecrypt, decryptor, CryptoStreamMode.Read);
baSavedKey = new byte[32];
//Read the data out of the crypto stream.
csDecrypt.Read(baSavedKey, 0, baSavedKey.Length);
SHA256 sha = new SHA256Managed();
byte[] newHash = sha.ComputeHash(baSavedKey);
for( int i = 0 ; i < 32; i++ )
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to get the stored key");
baSavedKey = null;
}
if (csDecrypt != null)
csDecrypt.Close();
if ( fsDecrypt != null )
fsDecrypt.Close();
return baSavedKey;
}
internal static void EncryptDataAndWriteToFile(byte[] xmlData,
byte[] key, string fileName)
{
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] baIV = GenerateAndSaveIV(fileName, myRijndael);
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, baIV);
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(xmlData);
fsEncrypt.Write(hash,0,hash.Length);
fsEncrypt.Flush();
#if CLEAR
byte[] dup = (byte[])xmlData.Clone();
// write clear file
FileStream fsClear = new FileStream(fileName + ".xml", FileMode.Create);
fsClear.Write(dup, 0, dup.Length);
fsClear.Flush();
fsClear.Close();
#endif
csEncrypt = new CryptoStream(fsEncrypt, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(xmlData, 0, xmlData.Length);
csEncrypt.FlushFinalBlock();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Encrypting and storing to file failed.");
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
}
internal static byte[] ReadFileAndDecryptData(byte[] key,
string fileName)
{
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
try
{
byte[] IV = new byte[16];
for(int z = 0 ; z < 16; z++ )
IV[z] = key[z];
//Get a decryptor that uses the same key and IV as the encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] baIV = RetrieveIV(fileName, IV);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, baIV);
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if(!File.Exists(fileName))
#endif
{
return null;
}
//Now decrypt
fsDecrypt = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] storedHash = new byte[HASH_SIZE];
fsDecrypt.Read(storedHash,0,storedHash.Length);
csDecrypt = new CryptoStream(fsDecrypt, decryptor, CryptoStreamMode.Read);
if(fsDecrypt.Length < HASH_SIZE )
{
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
ulong fileLen = (ulong)(fsDecrypt.Length - HASH_SIZE);
byte[] fromEncrypt = new byte[fileLen];
//Read the data out of the crypto stream.
int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
byte[] tmpEncrypt = new byte[bytesRead];
for(int i = 0 ; i < bytesRead; i++ )
tmpEncrypt[i] = fromEncrypt[i];
SHA256 sha = new SHA256Managed();
byte[] newHash = sha.ComputeHash(tmpEncrypt);
for( int i = 0 ; i < 32; i++ )
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
}
try
{
csDecrypt.Close();
}
catch { }
try
{
fsDecrypt.Close();
}
catch { }
return tmpEncrypt;
}
catch(Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
if (csDecrypt != null)
{
try
{
csDecrypt.Close();
}
catch
{
}
}
if( fsDecrypt != null )
{
try
{
fsDecrypt.Close();
}
catch
{
}
}
return null;
}
/* The methods EncryptData() and DecryptData() would be
* required when we use a database to store secrets.
*/
/* Encrypts the data with the key and returns the encrypted buffer.
*/
/*
internal static byte[] EncryptData(byte[] data, byte[] key)
{
try
{
byte[] IV = new byte[16];
int i = 0;
for(i = 0 ; i < 16; i++ )
IV[i] = key[i];
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream ms1 = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(ms1, encryptor, CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
return ms1.ToArray();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
*/
/* Decrypts the buffer(encrypted) with the key and returns the
* decrypted data.
*/
/*
internal static byte[] DecryptData(byte[] buffer, byte[] key)
{
try
{
byte[] IV = new byte[16];
for(int i = 0 ; i < 16; i++ )
IV[i] = key[i];
//Get a decryptor that uses the same key and IV as the encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream ms1 = new MemoryStream(buffer);
CryptoStream csDecrypt = new CryptoStream(ms1, decryptor, CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[buffer.Length];
//Read the data out of the crypto stream.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return fromEncrypt;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
return null;
}
*/
/* This method checks if we can get the master passcode by
* decrypting the passwds file ( where we store all possible
* passwds cross-encrypted.
*
* TBD : As we are storing master passcode and the keys in 2
* different files, we need to take care of cases when 1 of the files
* is deleted.
*/
internal static bool CheckIfMasterPasscodeIsAvailable(string desktopPasswd, string fileName)
{
return (File.Exists(fileName));
}
internal static byte[] GetMasterPasscode(string desktopPasswd, string fileName)
{
byte[] mp = DecryptMasterPasscodeUsingString(desktopPasswd, fileName, false);
return mp;
}
/* TBD - There must be a way, where we establish the integrity of
* the files where we store the keys and master passcode.
* Use a marker ?
*/
// Used to save the MasterPasscode encrypted with Desktop login, etc
internal static void EncryptAndStoreMasterPasscodeUsingString(
byte[] baMasterPasscode,
string passwd,
string fileName)
{
FileStream fsEncrypt = null;
CryptoStream csEncrypt = null;
try
{
if(File.Exists(fileName))
File.Delete(fileName);
byte[] baKey = Generate16ByteKeyFromString(passwd, null, false);
//Get an encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor;
encryptor = myRijndael.CreateEncryptor(baKey, GenerateAndSaveIV(fileName, myRijndael));
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName,FileMode.Create);
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
csEncrypt = new CryptoStream(fsEncrypt, encryptor,
CryptoStreamMode.Write);
//Write all data to the crypto stream and flush it.
csEncrypt.Write(baMasterPasscode, 0, baMasterPasscode.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Close();
fsEncrypt.Close();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
if (csEncrypt != null)
{
csEncrypt.Close();
}
if( fsEncrypt != null )
{
fsEncrypt.Close();
}
}
public static byte[] DecryptMasterPasscodeUsingString(string passwd,
string fileName, bool bTryOldMethod)
{
FileStream fsDecrypt = null;
CryptoStream csDecrypt = null;
byte[] baSavedMasterPasscode = null;
try
{
byte[] baKey = Generate16ByteKeyFromString(passwd, fileName, bTryOldMethod);
/* Get a decryptor that uses the same key and
* IV as the encryptor.
*/
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(baKey, RetrieveIV(fileName, baKey));
//Now decrypt
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if (!File.Exists(fileName))
#endif
{
return null;
}
fsDecrypt = new FileStream(fileName, FileMode.Open);
csDecrypt = new CryptoStream(fsDecrypt, decryptor,
CryptoStreamMode.Read);
baSavedMasterPasscode = new byte[16];
//Read the data out of the crypto stream.
csDecrypt.Read(baSavedMasterPasscode, 0, 16);
}
catch (Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to decrypt master passode");
baSavedMasterPasscode = null;
}
try
{
if (csDecrypt != null)
csDecrypt.Close();
}
catch { }
if (fsDecrypt != null)
fsDecrypt.Close();
return baSavedMasterPasscode;
}
internal static byte[] GetMasterPasscodeUsingMasterPasswd(
string mPasswd,
string fileName,
bool bUseOldMethod)
{
byte[] baMasterPasscode;
try
{
if(File.Exists(fileName))
{
/* Decrypt the passcode from the file using master passwd.
* and return the decrypted passcode.
*/
baMasterPasscode = DecryptMasterPasscodeUsingString(mPasswd, fileName, bUseOldMethod);
return baMasterPasscode;
}
else
return null;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Failed to get master passcode from master password.");
}
return null;
}
internal static byte[] GetMasterPasscodeUsingDesktopPasswd(
string desktopPasswd,
string fileName,
bool bUseOldMethod)
{
byte[] passcode;
try
{
if(File.Exists(fileName))
{
/* Decrypt the passcode from the file using desktop passwd.
* and return the decrypted passcode.
*/
passcode = DecryptMasterPasscodeUsingString(desktopPasswd,
fileName, bUseOldMethod);
return passcode;
}
else
return null;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Failed to get master passcode using desktop passwd");
}
return null;
}
//internal static string GenerateMasterPasscodeUsingDesktopPasswd(
internal static byte[] GenerateMasterPasscodeUsingString(
string desktopPasswd,
string fileName,
string validationFile,
UserIdentifier userId
)
{
try
{
byte[] baPasscode;
// use AES to generate a random 16 byte key;
RijndaelManaged myRijndael = new RijndaelManaged();
myRijndael.KeySize = 128;
//Create a new key and initialization vector.
myRijndael.GenerateKey();
baPasscode = myRijndael.Key;
EncryptAndStoreMasterPasscodeUsingString(baPasscode,
desktopPasswd,
fileName);
EncryptDataAndWriteToFile(
Encoding.Default.GetBytes(
ConstStrings.MICASA_VALIDATION_STRING),
baPasscode,
validationFile);
return baPasscode;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Generation of master passcode failed.");
}
return null;
}
public static bool ValidatePasscode(byte[] baPasscode, string fileName)
{
/* Here we decrpyt a well known string, throw exception
* if not successful
* A well-known string is encrpyted by the Passcode and saved
*/
CSSSLogger.DbgLog("Validate called");
if ((baPasscode == null) || baPasscode.Length < 1 )
return false;
try
{
byte[] baString = ReadFileAndDecryptData(baPasscode, fileName);
string sString = Encoding.Default.GetString(baString);
char[] trimChars = {'\0'};
sString = sString.TrimEnd(trimChars);
if( ConstStrings.MICASA_VALIDATION_STRING.Equals(sString))
{
CSSSLogger.DbgLog("Passed");
return true;
}
else
{
CSSSLogger.DbgLog("Failed");
return false;
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Validation of passcode failed.");
}
return false;
}
private static byte[] GenerateAndSaveIV(string sFileName, RijndaelManaged theRiManaged)
{
theRiManaged.GenerateIV();
byte[] baIV = theRiManaged.IV;
try
{
if (File.Exists(sFileName + ".IV"))
File.Delete(sFileName + ".IV");
// now save this
FileStream fs = new FileStream(sFileName + ".IV", FileMode.Create);
fs.Write(baIV, 0, 16);
fs.Flush();
fs.Close();
File.SetAttributes(sFileName + ".IV", FileAttributes.Hidden);
}
catch (Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
return baIV;
}
private static byte[] RetrieveIV(string sFileName, byte[] baOrigValue)
{
byte[] IV = new byte[16];
// check for file existence
try
{
FileStream fs = new FileStream(sFileName + ".IV", FileMode.Open);
fs.Read(IV, 0, 16);
fs.Close();
return IV;
}
catch (Exception e)
{
CSSSLogger.DbgLog(e.ToString());
}
// original IV size was 16 bytes, copy that much
if (baOrigValue.Length == 16)
{
return (byte[])baOrigValue.Clone();
}
else
{
for (int i=0; i<16; i++)
{
IV[i] = baOrigValue[i];
}
return IV;
}
}
private static void DumpIV(byte[] iv)
{
for (int i=0; i<iv.Length; i++)
{
Console.Write(iv[i] + " ");
}
Console.WriteLine("\r\n");
}
}
}

328
micasad/lss/FastRandom.cs Normal file
View File

@@ -0,0 +1,328 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Text;
namespace sscs.lss
{
/*
* Yes, if you want to go ahead and attach an LGPL header to the source
* file then that's fine. I hereby grant Novell Inc. permission to use the
* FastRandom.cs random number generator source code under the Lesser GNU
* Public Licesne (LGPL).
*
* Apr 19, 2006: received by jnorman@novell.com from Colin Green
*
* License also signed and sent to Novell on May 2, 2006.
*/
/// <summary>
/// A fast random number generator for .NET
/// Colin Green, January 2005
///
/// September 4th 2005
/// Added NextBytesUnsafe() - commented out by default.
/// Fixed bug in Reinitialise() - y,z and w variables were not being reset.
///
/// Key points:
/// 1) Based on a simple and fast xor-shift pseudo random number generator (RNG) specified in:
/// Marsaglia, George. (2003). Xorshift RNGs.
/// http://www.jstatsoft.org/v08/i14/xorshift.pdf
///
/// This particular implementation of xorshift has a period of 2^128-1. See the above paper to see
/// how this can be easily extened if you need a longer period. At the time of writing I could find no
/// information on the period of System.Random for comparison.
///
/// 2) Faster than System.Random. Up to 15x faster, depending on which methods are called.
///
/// 3) Direct replacement for System.Random. This class implements all of the methods that System.Random
/// does plus some additional methods. The like named methods are functionally equivalent.
///
/// 4) Allows fast re-initialisation with a seed, unlike System.Random which accepts a seed at construction
/// time which then executes a relatively expensive initialisation routine. This provides a vast speed improvement
/// if you need to reset the pseudo-random number sequence many times, e.g. if you want to re-generate the same
/// sequence many times. An alternative might be to cache random numbers in an array, but that approach is limited
/// by memory capacity and the fact that you may also want a large number of different sequences cached. Each sequence
/// can each be represented by a single seed value (int) when using FastRandom.
///
/// Notes.
/// A further performance improvement can be obtained by declaring local variables as static, thus avoiding
/// re-allocation of variables on each call. However care should be taken if multiple instances of
/// FastRandom are in use or if being used in a multi-threaded environment.
///
/// </summary>
public class FastRandom
{
// The +1 ensures NextDouble doesn't generate 1.0
const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0);
const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0);
const uint Y = 842502087, Z = 3579807591, W = 273326509;
uint x, y, z, w;
#region Constructors
/// <summary>
/// Initialises a new instance using time dependent seed.
/// </summary>
public FastRandom()
{
// Initialise using the system tick count.
Reinitialise((int)Environment.TickCount);
}
/// <summary>
/// Initialises a new instance using an int value as seed.
/// This constructor signature is provided to maintain compatibility with
/// System.Random
/// </summary>
public FastRandom(int seed)
{
Reinitialise(seed);
}
#endregion
#region Public Methods [Reinitialisation]
/// <summary>
/// Reinitialises using an int value as a seed.
/// </summary>
/// <param name="seed"></param>
public void Reinitialise(int seed)
{
// The only stipulation stated for the xorshift RNG is that at least one of
// the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing
// resetting of the x seed
x = (uint)seed;
y = Y;
z = Z;
w = W;
}
#endregion
#region Public Methods [Next* methods]
/// <summary>
/// Generates a uint. Values returned are over the full range of a uint,
/// uint.MinValue to uint.MaxValue, including the min and max values.
/// </summary>
/// <returns></returns>
public uint NextUInt()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
}
/// <summary>
/// Generates a random int. Values returned are over the range 0 to int.MaxValue-1.
/// MaxValue is not generated to remain functionally equivalent to System.Random.Next().
/// If you require an int from the full range, including negative values then call
/// NextUint() and cast the value to an int.
/// </summary>
/// <returns></returns>
public int Next()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
return (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))));
}
/// <summary>
/// Generates a random int over the range 0 to upperBound-1, and not including upperBound.
/// </summary>
/// <param name="upperBound"></param>
/// <returns></returns>
public int Next(int upperBound)
{
if (upperBound < 0)
throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0");
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// The explicit int cast before the first multiplication gives better performance.
// See comments in NextDouble.
return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * upperBound);
}
/// <summary>
/// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound.
/// upperBound must be >= lowerBound. lowerBound may be negative.
/// </summary>
/// <param name="lowerBound"></param>
/// <param name="upperBound"></param>
/// <returns></returns>
public int Next(int lowerBound, int upperBound)
{
if (lowerBound > upperBound)
throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound");
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// The explicit int cast before the first multiplication gives better performance.
// See comments in NextDouble.
int range = upperBound - lowerBound;
if (range < 0)
{ // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower).
// We also must use all 32 bits of precision, instead of the normal 31, which again is slower.
return lowerBound + (int)((REAL_UNIT_UINT * (double)(w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound));
}
// 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int anf gain
// a little more performance.
return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * (double)range);
}
/// <summary>
/// Generates a random double. Values returned are from 0.0 up to but not including 1.0.
/// </summary>
/// <returns></returns>
public double NextDouble()
{
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
// Here we can gain a 2x speed improvement by generating a value that can be cast to
// an int instead of the more easily available uint. If we then explicitly cast to an
// int the compiler will then cast the int to a double to perform the multiplication,
// this final cast is a lot faster than casting from a uint to a double. The extra cast
// to an int is very fast (the allocated bits remain the same) and so the overall effect
// of the extra cast is a significant performance improvement.
return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))));
}
/// <summary>
/// Fills the provided byte array with random bytes.
/// Increased performance is achieved by dividing and packaging bits directly from the
/// random number generator and storing them in 4 byte 'chunks'.
/// </summary>
/// <param name="buffer"></param>
public void NextBytes(byte[] buffer)
{
// Fill up the bulk of the buffer in chunks of 4 bytes at a time.
uint x = this.x, y = this.y, z = this.z, w = this.w;
int i = 0;
uint t;
for (; i < buffer.Length - 3; )
{
// Generate 4 bytes.
t = (x ^ (x << 11));
x = y; y = z; z = w;
w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
buffer[i++] = (byte)(w & 0x000000FF);
buffer[i++] = (byte)((w & 0x0000FF00) >> 8);
buffer[i++] = (byte)((w & 0x00FF0000) >> 16);
buffer[i++] = (byte)((w & 0xFF000000) >> 24);
}
// Fill up any remaining bytes in the buffer.
if (i < buffer.Length)
{
// Generate 4 bytes.
t = (x ^ (x << 11));
x = y; y = z; z = w;
w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
buffer[i++] = (byte)(w & 0x000000FF);
if (i < buffer.Length)
{
buffer[i++] = (byte)((w & 0x0000FF00) >> 8);
if (i < buffer.Length)
{
buffer[i++] = (byte)((w & 0x00FF0000) >> 16);
if (i < buffer.Length)
{
buffer[i] = (byte)((w & 0xFF000000) >> 24);
}
}
}
}
this.x = x; this.y = y; this.z = z; this.w = w;
}
// /// <summary>
// /// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation
// /// thus providing a nice speedup. Note that this requires the unsafe compilation flag to be specified
// /// and so is commented out by default.
// /// </summary>
// /// <param name="buffer"></param>
// public unsafe void NextBytesUnsafe(byte[] buffer)
// {
// if(buffer.Length % 4 != 0)
// throw new ArgumentException("Buffer length must be divisible by 4", "buffer");
//
// uint x=this.x, y=this.y, z=this.z, w=this.w;
// uint t;
//
// fixed(byte* pByte0 = buffer)
// {
// uint* pDWord = (uint*)pByte0;
// for(int i = 0, len = buffer.Length>>2; i < len; i++)
// {
// t=(x^(x<<11));
// x=y; y=z; z=w;
// *pDWord++ = w = (w^(w>>19))^(t^(t>>8));
// }
// }
//
// this.x=x; this.y=y; this.z=z; this.w=w;
// }
// Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned
// with bitBufferIdx.
uint bitBuffer;
int bitBufferIdx = 32;
/// <summary>
/// Generates random bool.
/// Increased performance is achieved by buffering 32 random bits for
/// future calls. Thus the random number generator is only invoked once
/// in every 32 calls.
/// </summary>
/// <returns></returns>
public bool NextBool()
{
if (bitBufferIdx == 32)
{
// Generate 32 more bits.
uint t = (x ^ (x << 11));
x = y; y = z; z = w;
bitBuffer = w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
// Reset the idx that tells us which bit to read next.
bitBufferIdx = 1;
return (bitBuffer & 0x1) == 1;
}
bitBufferIdx++;
return ((bitBuffer >>= 1) & 0x1) == 1;
}
#endregion
}
}

520
micasad/lss/LocalStorage.cs Normal file
View File

@@ -0,0 +1,520 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Security.Cryptography;
using System.Xml;
#if LINUX
using Mono.Unix.Native;
#endif
using sscs.cache;
using sscs.crypto;
using sscs.common;
using sscs.constants;
using Novell.CASA.MiCasa.Common;
namespace sscs.lss
{
/// <summary>
/*
* This class is a service to store data persistently.
* How it does this is determined by implementation within the
* private methods (File system using file(s), database, etc)
* The MasterPasscode can be used to generate the key for
* encyption and decryption.
* If encrpytion is used, the private methods will also manage
* how the encyption key is to be stored and retrieved.
* Each piece of data is located by a DataID.
* This might be an individual credentail or
* a complete store.
*/
/* We might not need this as a separate class.
* Depending on the db changes, we can change this later.
*/
/// </summary>
public class LocalStorage
{
private byte[] m_baGeneratedKey = null;
private SecretStore userStore = null;
private int persistThreadSleepTime = 1000 * 60 * 5; //1000 * 30;
private Thread persistThread = null;
#if LINUX
Mono.Unix.UnixFileSystemInfo sockFileInfo;
Mono.Unix.UnixUserInfo sockFileOwner;
#endif
private static string LINUXID = "Unix";
internal LocalStorage(SecretStore store,byte[] baMasterPasscode)
{
userStore = store;
m_baGeneratedKey = baMasterPasscode;
LoadPersistentStore();
userStore.DumpSecretstore();
}
~LocalStorage()
{
if(persistThread != null)
{
persistThread.Abort();
persistThread.Join();
}
}
// allowing a user to choose the storage location is not approved yet
private LocalStorage(SecretStore store,
byte[] baMasterPasscode, string sStorageDirectory)
{
userStore = store;
m_baGeneratedKey = baMasterPasscode;
LoadPersistentStore();
userStore.DumpSecretstore();
}
private void StorePersistentData(string sDataID, byte[] baData)
{
}
private byte[] RetrievePersistentData(string sDataID)
{
return null;
}
public void PersistStoreWithDelay()
{
if (persistThread == null)
{
persistThread = new Thread(new ThreadStart(PersistStoreDelayThreadFn));
persistThread.Start();
}
}
public bool StopPersistence()
{
if(persistThread != null)
{
persistThread.Abort();
persistThread.Join();
}
return true;
}
public bool IsOwnedByRoot(string fileName)
{
#if LINUX
sockFileInfo = new Mono.Unix.UnixFileInfo(fileName);
sockFileOwner = sockFileInfo.OwnerUser;
if(0==sockFileOwner.UserId)
return true;
else
return false;
#else
return true;
#endif
}
private string GetDecryptedXml()
{
try
{
string fileName = userStore.GetPersistenceFilePath();
string tempFile = fileName;
int count = 0;
if(!File.Exists(fileName))
{
while(true)
{
// check for tmp file
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
{
File.Move(tempFile+".tmp", fileName);
break;
}
else
{
count++;
tempFile = fileName + count.ToString();
}
}
else
return null;
}
// delete tmp file if there
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
File.Delete(tempFile+".tmp");
}
}
byte[] baPasscode = null;
if (null != m_baGeneratedKey)
baPasscode = m_baGeneratedKey;
else
baPasscode = CASACrypto.GetMasterPasscode(userStore.GetDesktopPasswd(),userStore.GetPasscodeByDesktopFilePath());
if( null == baPasscode )
return null;
byte[] key = CASACrypto.GetKeySetFromFile(baPasscode,userStore.GetKeyFilePath());
if( null == key )
return null;
byte[] decryptedBuffer = CASACrypto.ReadFileAndDecryptData(key,fileName);
if( null == decryptedBuffer )
return null;
string temp = Encoding.UTF8.GetString(decryptedBuffer, 0, decryptedBuffer.Length);
return temp;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to get persistent store");
}
return null;
}
/* This method, uses the key to decrypt the persistent store
* and populates userStore with the persistent data.
*/
private bool LoadPersistentStore()
{
try
{
string xpath = "";
XmlDocument doc = new XmlDocument();
string xmlToLoad = GetDecryptedXml();
if(xmlToLoad != null)
{
doc.LoadXml(xmlToLoad);
#if false
XmlTextWriter writer = new XmlTextWriter("/home/poorna/.miCASA.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
#endif
}
else
{
return false;
}
xpath = "//" + XmlConsts.miCASANode;
XmlNode miCASANode = doc.SelectSingleNode(xpath);
if(miCASANode != null)
{
xpath = "descendant::" + XmlConsts.keyChainNode;
XmlNodeList keyChainNodeList = miCASANode.SelectNodes(xpath);
foreach(XmlNode node in keyChainNodeList)
{
XmlAttributeCollection attrColl = node.Attributes;
string keyChainId = (attrColl[XmlConsts.idAttr]).Value + "\0";
KeyChain keyChain = null;
if( userStore.CheckIfKeyChainExists(keyChainId) == false )
{
keyChain = new KeyChain(keyChainId);
userStore.AddKeyChain(keyChain);
}
else
{
keyChain = userStore.GetKeyChain(keyChainId);
}
xpath = "descendant::" + XmlConsts.secretNode;
XmlNodeList secretNodeList = node.SelectNodes(xpath);
foreach(XmlNode secretNode in secretNodeList)
{
attrColl = secretNode.Attributes;
string secretId = (attrColl[XmlConsts.idAttr]).Value + "\0";
xpath = "descendant::" + XmlConsts.valueNode;
Secret secret = new Secret(secretId);
if( keyChain.CheckIfSecretExists(secretId) == false)
{
keyChain.AddSecret(secret);
XmlNode secretValNode = (secretNode.SelectSingleNode(xpath));
xpath = "descendant::" + XmlConsts.keyNode;
XmlNodeList keyNodeList = secretValNode.SelectNodes(xpath);
secret = keyChain.GetSecret(secretId);
foreach(XmlNode keyNode in keyNodeList)
{
attrColl = keyNode.Attributes;
string key;
try
{
key = (attrColl[XmlConsts.idAttr]).Value;
}
catch (Exception)
{
// LinkedKey node, continue
continue;
}
xpath = "descendant::" + XmlConsts.keyValueNode;
XmlNode keyValNode = keyNode.SelectSingleNode(xpath);
string keyValue = keyValNode.InnerText;
secret.SetKeyValue(key,keyValue);
// add linked keys
xpath = "descendant::" + XmlConsts.linkedKeyNode;
XmlNodeList linkNodeList = keyNode.SelectNodes(xpath);
foreach(XmlNode linkNode in linkNodeList)
{
// get TargetSecretID
xpath = "descendant::" + XmlConsts.linkedTargetSecretNode;
XmlNode targetSecretNode = linkNode.SelectSingleNode(xpath);
string sSecretID = targetSecretNode.InnerText + "\0";
// get TargetSecretKey
xpath = "descendant::" + XmlConsts.linkedTargetKeyNode;
XmlNode targetKeyNode = linkNode.SelectSingleNode(xpath);
string sKeyID = targetKeyNode.InnerText;
LinkedKeyInfo lki = new LinkedKeyInfo(sSecretID, sKeyID, true);
KeyValue kv = secret.GetKeyValue(key);
kv.AddLink(lki);
}
}
}//if ends
}
}//end of traversing keyChainNodeList
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
// collect now to remove old data from memory
GC.Collect();
return true;
}
private void PersistStoreDelayThreadFn()
{
Thread.Sleep(15000);
PersistStore();
persistThread = null;
}
private void PersistStoreThreadFn()
{
while(true)
{
Thread.Sleep(persistThreadSleepTime);
PersistStore();
}
}
/* Persists the store to an xml file.
* TBD : Would we require any form of encoding?
*/
internal void PersistStore()
{
// userStore.DumpSecretstore();
try
{
MemoryStream ms1 = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms1,null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement(XmlConsts.miCASANode);
writer.WriteAttributeString(XmlConsts.versionAttr,"1.5");
{
IDictionaryEnumerator iter = (IDictionaryEnumerator)userStore.GetKeyChainEnumerator();
char [] tmpId;
string sTmpId;
while( iter.MoveNext() )
{
KeyChain kc = (KeyChain)iter.Value;
writer.WriteStartElement(XmlConsts.keyChainNode);
string kcId = kc.GetKey();
tmpId = new char[kcId.Length-1];
for(int i = 0; i < kcId.Length-1; i++ )
tmpId[i] = kcId[i];
sTmpId = new string(tmpId);
writer.WriteAttributeString(XmlConsts.idAttr,sTmpId);
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,kc.CreatedTime.ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,kc.ModifiedTime.ToString());
writer.WriteEndElement();
*/
IDictionaryEnumerator secIter = (IDictionaryEnumerator)(kc.GetAllSecrets());
while(secIter.MoveNext())
{
Secret secret = (Secret)secIter.Value;
writer.WriteStartElement(XmlConsts.secretNode);
string secretId = secret.GetKey();
tmpId = new char[secretId.Length-1];
for(int i = 0; i < secretId.Length-1; i++ )
tmpId[i] = secretId[i];
sTmpId = new string(tmpId);
writer.WriteAttributeString(XmlConsts.idAttr,sTmpId);
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,secret.CreatedTime.ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,secret.ModifiedTime.ToString());
writer.WriteEndElement();
*/
writer.WriteStartElement(XmlConsts.valueNode);
// byte[] byteArr = secret.GetValue();
IDictionaryEnumerator etor = (IDictionaryEnumerator)secret.GetKeyValueEnumerator();
while(etor.MoveNext())
{
string sKey = (string)etor.Key;
string value = secret.GetKeyValue(sKey).GetValue();
writer.WriteStartElement(XmlConsts.keyNode);
writer.WriteAttributeString(XmlConsts.idAttr, sKey);
writer.WriteStartElement(XmlConsts.keyValueNode);
writer.WriteString(value);
writer.WriteEndElement();
/* If we need to store time
writer.WriteStartElement(XmlConsts.timeNode);
writer.WriteAttributeString(XmlConsts.createdTimeNode,(secret.GetKeyValueCreatedTime(sKey)).ToString());
writer.WriteAttributeString(XmlConsts.modifiedTimeNode,(secret.GetKeyValueModifiedTime(sKey)).ToString());
writer.WriteEndElement();
*/
// write all LinkKeys
Hashtable htLinkedKeys = secret.GetLinkedKeys(sKey);
if (htLinkedKeys != null)
{
IDictionaryEnumerator etorLinked = (IDictionaryEnumerator)htLinkedKeys.GetEnumerator();
while(etorLinked.MoveNext())
{
LinkedKeyInfo lki = (LinkedKeyInfo)etorLinked.Value;
writer.WriteStartElement(XmlConsts.linkedKeyNode);
writer.WriteStartElement(XmlConsts.linkedTargetSecretNode);
writer.WriteString(lki.GetLinkedSecretID().Substring(0, lki.GetLinkedSecretID().Length-1));
writer.WriteEndElement();
writer.WriteStartElement(XmlConsts.linkedTargetKeyNode);
writer.WriteString(lki.GetLinkedKeyID());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
/*
char[] chArr = new char[byteArr.Length];
for(int z = 0; z < byteArr.Length; z++)
chArr[z] = (char)byteArr[z];
string stringToStore = new string(chArr);
writer.WriteString(stringToStore);
*/
writer.WriteEndElement(); //end of value node
writer.WriteEndElement();
}
writer.WriteEndElement(); //keychain
}
}
writer.WriteEndElement(); //miCASA node
writer.WriteEndDocument();
writer.Flush();
writer.Close();
//byte[] key = CASACrypto.GetKeySetFromFile(CASACrypto.GetMasterPasscode(userStore.GetDesktopPasswd(),userStore.GetPasscodeByDesktopFilePath()),userStore.GetKeyFilePath());
byte[] key = CASACrypto.GetKeySetFromFile(m_baGeneratedKey, userStore.GetKeyFilePath());
string fileName = userStore.GetPersistenceFilePath();
string tempFile = fileName;
int count=0;
// rename existing file
if(File.Exists(fileName))
{
while(true)
{
if (File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
{
File.Delete(tempFile+".tmp");
break;
}
else
{
count++;
tempFile = fileName + count.ToString();
}
}
else
break;
}
File.Move(fileName, tempFile+".tmp");
}
CASACrypto.EncryptDataAndWriteToFile(ms1.ToArray(),key,fileName);
//remove temp
if(File.Exists(tempFile+".tmp"))
{
if(IsOwnedByRoot(tempFile+".tmp"))
File.Delete(tempFile+".tmp");
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
}
}
}

View File

@@ -0,0 +1,270 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
//
// Rfc2898DeriveBytes.cs: RFC2898 (PKCS#5 v2) Key derivation for Password Based Encryption
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//using System.Runtime.InteropServices;
using System;
using System.Text;
using System.Security.Cryptography;
using sscs.lss;
namespace sscs.crypto {
//[ComVisible (true)]
public class Rfc2898DeriveBytes : DeriveBytes {
private const int defaultIterations = 1000;
private int _iteration;
private byte[] _salt;
private HMACSHA1 _hmac;
private byte[] _buffer;
private int _pos;
private int _f;
// constructors
public Rfc2898DeriveBytes (string password, byte[] salt)
: this (password, salt, defaultIterations)
{
}
public Rfc2898DeriveBytes (string password, byte[] salt, int iterations)
{
if (password == null)
throw new ArgumentNullException ("password");
Salt = salt;
IterationCount = iterations;
_hmac = new HMACSHA1 (Encoding.UTF8.GetBytes (password));
}
public Rfc2898DeriveBytes (byte[] password, byte[] salt, int iterations)
{
if (password == null)
throw new ArgumentNullException ("password");
Salt = salt;
IterationCount = iterations;
_hmac = new HMACSHA1 (password);
}
public Rfc2898DeriveBytes (string password, int saltSize)
: this (password, saltSize, defaultIterations)
{
}
public Rfc2898DeriveBytes(string password, int saltSize, int iterations)
: this (password, saltSize, iterations, false)
{
}
public Rfc2898DeriveBytes (string password, int saltSize, int iterations, bool bUseOldMethod)
{
if (password == null)
throw new ArgumentNullException ("password");
if (saltSize < 0)
throw new ArgumentOutOfRangeException ("invalid salt length");
if (bUseOldMethod)
{
Salt = GenerateOldSalt(password, saltSize);
}
else
{
Salt = GenerateNewSalt(password, saltSize);
}
IterationCount = iterations;
_hmac = new HMACSHA1 (Encoding.UTF8.GetBytes (password));
}
private static byte[] GenerateOldSalt(string password, int saltSize)
{
byte[] buffer = new byte[saltSize];
Random rand = new Random(password.GetHashCode());
rand.NextBytes(buffer);
return buffer;
}
private static byte[] GenerateNewSalt(string password, int saltSize)
{
int j = 0;
byte[] buffer = new byte[saltSize];
// iterate thru each character, creating a new Random,
// getting 2 bytes from each, until our salt buffer is full.
for (int i = 0; i < password.Length;)
{
char letter = password[i];
int iLetter = (int)letter;
FastRandom ranNum = new FastRandom(iLetter * (j+1));
byte[] temp = new byte[2];
ranNum.NextBytes(temp);
for (int k = 0; k < temp.Length; k++)
{
buffer[j++] = temp[k];
// get out if buffer is full
if (j >= saltSize)
{
return buffer;
}
}
i++;
// reset i if at end of password
if ((i + 1) > password.Length)
{
i = 0;
}
}
return buffer;
}
// properties
public int IterationCount
{
get { return _iteration; }
set {
if (value < 1)
throw new ArgumentOutOfRangeException ("IterationCount < 1");
_iteration = value;
}
}
public byte[] Salt {
get { return (byte[]) _salt.Clone (); }
set {
if (value == null)
throw new ArgumentNullException ("Salt");
if (value.Length < 8)
throw new ArgumentException ("Salt < 8 bytes");
_salt = (byte[])value.Clone ();
}
}
// methods
private byte[] F (byte[] s, int c, int i)
{
byte[] data = new byte [s.Length + 4];
Buffer.BlockCopy (s, 0, data, 0, s.Length);
byte[] int4 = BitConverter.GetBytes (i);
Array.Reverse (int4, 0, 4);
Buffer.BlockCopy (int4, 0, data, s.Length, 4);
// this is like j=0
byte[] u1 = _hmac.ComputeHash (data);
data = u1;
// so we start at j=1
for (int j=1; j < c; j++) {
byte[] un = _hmac.ComputeHash (data);
// xor
for (int k=0; k < 20; k++)
u1 [k] = (byte)(u1 [k] ^ un [k]);
data = un;
}
return u1;
}
public override byte[] GetBytes (int cb)
{
if (cb < 1)
throw new ArgumentOutOfRangeException ("cb");
int l = cb / 20; // HMACSHA1 == 160 bits == 20 bytes
int r = cb % 20; // remainder
if (r != 0)
l++; // rounding up
byte[] result = new byte [cb];
int rpos = 0;
if (_pos > 0) {
int count = Math.Min (20 - _pos, cb);
Buffer.BlockCopy (_buffer, _pos, result, 0, count);
if (count >= cb)
return result;
_pos = 0;
rpos = 20 - cb;
r = cb - rpos;
}
for (int i=1; i <= l; i++) {
_buffer = F (_salt, _iteration, ++_f);
int count = ((i == l) ? r : 20);
Buffer.BlockCopy (_buffer, _pos, result, rpos, count);
rpos += _pos + count;
_pos = ((count == 20) ? 0 : count);
}
return result;
}
public override void Reset ()
{
_buffer = null;
_pos = 0;
_f = 0;
}
}
}

406
micasad/micasad.csproj Normal file
View File

@@ -0,0 +1,406 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.10.3077"
SchemaVersion = "2.0"
ProjectGuid = "{E39D2266-AB30-430E-A466-AC909363A830}"
>
<Build>
<Settings
ApplicationIcon = ""
AssemblyKeyContainerName = ""
AssemblyName = "micasad"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "Exe"
PreBuildEvent = ""
PostBuildEvent = ""
RootNamespace = "sscs"
RunPostBuildEvent = "OnBuildSuccess"
StartupObject = "sscs.init.WinSecretStoreClientService"
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE;W32"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "false"
OutputPath = "bin\Debug\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE; W32"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System.Configuration.Install"
AssemblyName = "System.Configuration.Install"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Configuration.Install.dll"
/>
<Reference
Name = "System.Data"
AssemblyName = "System.Data"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll"
/>
<Reference
Name = "System"
AssemblyName = "System"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll"
/>
<Reference
Name = "System.Management"
AssemblyName = "System.Management"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Management.dll"
/>
<Reference
Name = "System.ServiceProcess"
AssemblyName = "System.ServiceProcess"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.ServiceProcess.dll"
/>
<Reference
Name = "System.XML"
AssemblyName = "System.Xml"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll"
/>
<Reference
Name = "System.Windows.Forms"
AssemblyName = "System.Windows.Forms"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Windows.Forms.dll"
/>
<Reference
Name = "Accessibility"
AssemblyName = "Accessibility"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Accessibility.dll"
/>
<Reference
Name = "System.Drawing"
AssemblyName = "System.Drawing"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Drawing.dll"
/>
<Reference
Name = "System.Runtime.Serialization.Formatters.Soap"
AssemblyName = "System.Runtime.Serialization.Formatters.Soap"
HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Runtime.Serialization.Formatters.Soap.dll"
/>
<Reference
Name = "Novell.CASA.Common"
Project = "{57CD94A2-5B4A-40C3-8189-CB760FB78357}"
Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
/>
<Reference
Name = "AppModule.InterProcessComm"
Project = "{E98F1F7E-40B6-44C8-AC66-EC867B141FA1}"
Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
/>
<Reference
Name = "AppModule.NamedPipes"
Project = "{077B53BB-404A-4B2F-BA17-AAE98C5E9C66}"
Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\IKeychain.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\ISecret.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\KeyChain.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\KeyValue.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\Secret.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cache\SecretStore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\Constants.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\CSSSException.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\CSSSLogger.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\RequestParser.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\SessionManager.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\User.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\UserIdentifier.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\WinUser.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "common\WinUserIdentifier.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\CommunicationFactory.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\ICommunication.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\IPCChannel.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\WinCommunication.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\WinIPCChannel.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\win\PipeManager.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "communication\win\ServerNamedPipe.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "init\AppHandler.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "init\CredMgr.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "init\ProjectInstaller.cs"
SubType = "Component"
BuildAction = "Compile"
/>
<File
RelPath = "init\ProjectInstaller.resx"
DependentUpon = "ProjectInstaller.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "init\WinSecretStoreClientService.cs"
SubType = "Component"
BuildAction = "Compile"
/>
<File
RelPath = "init\WinSecretStoreClientService.resx"
DependentUpon = "WinSecretStoreClientService.cs"
BuildAction = "EmbeddedResource"
/>
<File
RelPath = "lss\CASACrypto.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "lss\FastRandom.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "lss\LocalStorage.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "lss\Rfc2898DeriveBytes.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<Folder RelPath = "startup\" />
<File
RelPath = "verbs\AddKeyChain.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\CloseSecretStore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\EnumerateKeyChainIds.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\EnumerateSecretIds.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\GetSecretStoreInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\IsSecretPersistent.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\ISSVerb.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\ObjectSerialization.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\OpenSecretStore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\ReadBinaryKey.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\ReadKey.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\ReadSecret.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\RemoveKeyChain.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\RemoveSecret.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\RemoveSecretStore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\SetMasterPasscode.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\SetMasterPassword.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\WriteBinaryKey.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\WriteKey.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "verbs\WriteSecret.cs"
SubType = "Code"
BuildAction = "Compile"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>

View File

@@ -0,0 +1,48 @@
<VisualStudioProject>
<CSHARP LastOpenVersion = "7.10.3077" >
<Build>
<Settings ReferencePath = "" >
<Config
Name = "Debug"
EnableASPDebugging = "false"
EnableASPXDebugging = "false"
EnableUnmanagedDebugging = "false"
EnableSQLServerDebugging = "false"
RemoteDebugEnabled = "false"
RemoteDebugMachine = ""
StartAction = "Project"
StartArguments = "/Standalone"
StartPage = ""
StartProgram = ""
StartURL = ""
StartWorkingDirectory = ""
StartWithIE = "true"
/>
<Config
Name = "Release"
EnableASPDebugging = "false"
EnableASPXDebugging = "false"
EnableUnmanagedDebugging = "false"
EnableSQLServerDebugging = "false"
RemoteDebugEnabled = "false"
RemoteDebugMachine = ""
StartAction = "Project"
StartArguments = "/Standalone"
StartPage = ""
StartProgram = ""
StartURL = ""
StartWorkingDirectory = ""
StartWithIE = "false"
/>
</Settings>
</Build>
<OtherProjectSettings
CopyProjectDestinationFolder = ""
CopyProjectUncPath = ""
CopyProjectOption = "0"
ProjectView = "ShowAllFiles"
ProjectTrust = "0"
/>
</CSHARP>
</VisualStudioProject>

60
micasad/objs.lux Normal file
View File

@@ -0,0 +1,60 @@
OBJS=\
AssemblyInfo \
init/Main \
init/AppHandler \
common/RequestParser \
common/SessionManager \
common/User \
common/UnixUser \
common/UserIdentifier \
common/UnixUserIdentifier \
common/Constants \
common/CSSSLogger \
common/CSSSException \
communication/IPCChannel \
communication/CommunicationFactory \
communication/UnixIPCChannel \
communication/ICommunication \
communication/UnixCommunication \
cache/KeyChain \
cache/Secret \
cache/SecretStore \
cache/KeyValue \
cache/IKeychain \
cache/ISecret \
lss/LocalStorage \
lss/CASACrypto \
lss/Rfc2898DeriveBytes \
verbs/ISSVerb \
verbs/GetSecretStoreInfo \
verbs/OpenSecretStore \
verbs/CloseSecretStore \
verbs/RemoveSecretStore \
verbs/AddKeyChain \
verbs/RemoveKeyChain \
verbs/WriteSecret \
verbs/ReadSecret \
verbs/RemoveSecret \
verbs/EnumerateKeyChainIds \
verbs/EnumerateSecretIds \
verbs/SetMasterPassword \
verbs/WriteKey \
verbs/ReadKey \
verbs/WriteBinaryKey \
verbs/ReadBinaryKey \
verbs/IsSecretPersistent \
verbs/ObjectSerialization \
test/cache/TestSecret \
test/cache/TestKeyChain \
test/cache/TestSecretStore \
test/common/TestSessionManager \
test/common/TestRequestParser \
test/communication/TestUnixCommunication \
test/verbs/TestOpenSecretStore \
test/verbs/TestCloseSecretStore \
test/verbs/TestEnumerateKeyChainIDs \
test/verbs/TestEnumerateSecIDs \
test/verbs/TestReadSecret \
test/verbs/TestRemoveKeyChain \
test/verbs/TestWriteSecret

77
micasad/objs.w32 Normal file
View File

@@ -0,0 +1,77 @@
OBJS=\
init/WinSecretStoreClientService \
init/ProjectInstaller \
init/AppHandler \
common/RequestParser \
common/SessionManager \
common/User \
common/WinUser \
common/UserIdentifier \
common/WinUserIdentifier \
common/NsscsFile \
common/Constants \
common/TrustedProcess \
common/CSSSLogger \
common/CSSSException \
communication/win/InterProcessComm/IChannelManager \
communication/win/InterProcessComm/IClientChannel \
communication/win/InterProcessComm/IInterProcessConnection \
communication/win/InterProcessComm/InterProcessConnectionState \
communication/win/InterProcessComm/InterProcessIOException \
communication/win/NamedPipes/APipeConnection \
communication/win/NamedPipes/ClientPipeConnection \
communication/win/NamedPipes/NamedPipeIOException \
communication/win/NamedPipes/NamedPipeNative \
communication/win/NamedPipes/NamedPipeWrapper \
communication/win/NamedPipes/PipeHandle \
communication/win/NamedPipes/PipeManager \
communication/win/NamedPipes/ServerNamedPipe \
communication/win/NamedPipes/ServerPipeConnection \
communication/IPCChannel \
communication/CommunicationFactory \
communication/WinIPCChannel \
communication/ICommunication \
communication/WinCommunication \
cache/KeyChain \
cache/Secret \
cache/SecretStore \
cache/Time \
cache/Value \
cache/Eprotect \
cache/IKeychain \
cache/ISecret \
lss/LocalSecretStore \
lss/CASACrypto \
lss/Rfc2898DeriveBytes \
verbs/ISSVerb \
verbs/GetSecretStoreInfo \
verbs/OpenSecretStore \
verbs/CloseSecretStore \
verbs/RemoveSecretStore \
verbs/AddKeyChain \
verbs/RemoveKeyChain \
verbs/WriteSecret \
verbs/ReadSecret \
verbs/RemoveSecret \
verbs/WriteKey \
verbs/ReadKey \
verbs/SetWorkStationPasswd \
verbs/SetPassCode \
verbs/NotifyUserState \
verbs/GetUserState \
verbs/IsSecretPersistent.cs \
verbs/SetMasterPassword.cs \
verbs/EnumerateKeyChainIds \
verbs/EnumerateSecretIds \
test/cache/TestSecret.cs \
test/cache/TestKeyChain.cs \
test/cache/TestSecretStore.cs \
test/common/TestSessionManager.cs \
test/common/TestRequestParser.cs \
test/verbs/TestOpenSecretStore.cs \
test/verbs/TestCloseSecretStore.cs \
test/verbs/TestEnumerateKeyChainIDs.cs \
test/verbs/TestEnumerateSecIDs.cs \
test/verbs/TestReadSecret.cs \
test/verbs/TestRemoveKeyChain.cs \
test/verbs/TestWriteSecret.cs

61
micasad/src.lux Normal file
View File

@@ -0,0 +1,61 @@
SRC=\
AssemblyInfo.cs \
init/Main.cs \
init/AppHandler.cs \
common/RequestParser.cs \
common/SessionManager.cs \
common/User.cs \
common/UnixUser.cs \
common/UserIdentifier.cs \
common/UnixUserIdentifier.cs \
common/Constants.cs \
common/CSSSLogger.cs \
common/CSSSException.cs \
communication/IPCChannel.cs \
communication/CommunicationFactory.cs \
communication/UnixIPCChannel.cs \
communication/ICommunication.cs \
communication/UnixCommunication.cs \
cache/KeyChain.cs \
cache/Secret.cs \
cache/SecretStore.cs \
cache/KeyValue.cs \
cache/IKeychain.cs \
cache/ISecret.cs \
lss/LocalStorage.cs \
lss/CASACrypto.cs \
lss/Rfc2898DeriveBytes.cs \
verbs/ISSVerb.cs \
verbs/GetSecretStoreInfo.cs \
verbs/OpenSecretStore.cs \
verbs/CloseSecretStore.cs \
verbs/RemoveSecretStore.cs \
verbs/AddKeyChain.cs \
verbs/RemoveKeyChain.cs \
verbs/WriteSecret.cs \
verbs/ReadSecret.cs \
verbs/RemoveSecret.cs \
verbs/EnumerateKeyChainIds.cs \
verbs/EnumerateSecretIds.cs \
verbs/SetMasterPassword.cs \
verbs/WriteKey.cs \
verbs/ReadKey.cs \
verbs/WriteBinaryKey.cs \
verbs/ReadBinaryKey.cs \
verbs/IsSecretPersistent.cs \
verbs/ObjectSerialization.cs \
test/cache/TestSecret.cs \
test/cache/TestKeyChain.cs \
test/cache/TestSecretStore.cs \
test/common/TestSessionManager.cs \
test/common/TestRequestParser.cs \
test/communication/TestUnixCommunication.cs \
test/verbs/TestOpenSecretStore.cs \
test/verbs/TestCloseSecretStore.cs \
test/verbs/TestEnumerateKeyChainIDs.cs \
test/verbs/TestEnumerateSecIDs.cs \
test/verbs/TestReadSecret.cs \
test/verbs/TestRemoveKeyChain.cs \
test/verbs/TestWriteSecret.cs

57
micasad/src.w32 Normal file
View File

@@ -0,0 +1,57 @@
SRC=\
init\\WinSecretStoreClientService.cs \
init\\ProjectInstaller.cs \
init\\AppHandler.cs \
common\\RequestParser.cs \
common\\SessionManager.cs \
common\\User.cs \
common\\WinUser.cs \
common\\UserIdentifier.cs \
common\\WinUserIdentifier.cs \
common\\Constants.cs \
common\\CSSSLogger.cs \
common\\CSSSException.cs \
communication\\win\\InterProcessComm\\IChannelManager.cs \
communication\\win\\InterProcessComm\\IClientChannel.cs \
communication\\win\\InterProcessComm\\IInterProcessConnection.cs \
communication\\win\\InterProcessComm\\InterProcessConnectionState.cs \
communication\\win\\InterProcessComm\\InterProcessIOException.cs \
communication\\win\\NamedPipes\\APipeConnection.cs \
communication\\win\\NamedPipes\\ClientPipeConnection.cs \
communication\\win\\NamedPipes\\NamedPipeIOException.cs \
communication\\win\\NamedPipes\\NamedPipeNative.cs \
communication\\win\\NamedPipes\\NamedPipeWrapper.cs \
communication\\win\\NamedPipes\\PipeHandle.cs \
communication\\win\\NamedPipes\\PipeManager.cs \
communication\\win\\NamedPipes\\ServerNamedPipe.cs \
communication\\win\\NamedPipes\\ServerPipeConnection.cs \
communication\\IPCChannel.cs \
communication\\CommunicationFactory.cs \
communication\\WinIPCChannel.cs \
communication\\ICommunication.cs \
communication\\WinCommunication.cs \
lss\\LocalStorage.cs\
lss\\CASACrypto.cs\
lss\\Rfc2898DeriveBytes.cs\
cache\\KeyValue.cs\
cache\\KeyChain.cs \
cache\\Secret.cs \
cache\\SecretStore.cs \
cache\\IKeychain.cs \
cache\\ISecret.cs \
verbs\\ISSVerb.cs \
verbs\\GetSecretStoreInfo.cs \
verbs\\OpenSecretStore.cs \
verbs\\CloseSecretStore.cs \
verbs\\RemoveSecretStore.cs \
verbs\\AddKeyChain.cs \
verbs\\RemoveKeyChain.cs \
verbs\\WriteSecret.cs \
verbs\\ReadSecret.cs \
verbs\\RemoveSecret.cs \
verbs\\ReadKey.cs \
verbs\\WriteKey.cs \
verbs\\IsSecretPersistent.cs \
verbs\\SetMasterPassword.cs \
verbs\\EnumerateKeyChainIds.cs \
verbs\\EnumerateSecretIds.cs

108
micasad/startup/Makefile.am Normal file
View File

@@ -0,0 +1,108 @@
#######################################################################
#
# Copyright (C) 2006 Novell, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#######################################################################
if DEBUG
TARGET_CFG = Debug
CFLAGS += -v -w
else
TARGET_CFG = Release
endif
SUBDIRS =
DIST_SUBDIRS =
EXTRA_DIST = $(CFILES) *.sh *casa*
CASAROOT = ../..
CASALIBDIR = $(CASAROOT)/$(LIB)
if LIB64
CASABINDIR = $(CASAROOT)/bin64
else
CASABINDIR = $(CASAROOT)/bin
endif
# handle Mono secondary dependencies
export MONO_PATH := $(MONO_PATH)
PLATFORMINDEPENDENTSOURCEDIR = ..
PLATFORMDEPENDENTSOURCEDIR = .
MODULE_NAME =micasad-init
MODULE_EXT =
CFILES = micasad-init.c
CSFILES_CSC :=
EXTRA_CFLAGS =
RESOURCES =
OBJDIR = ./$(TARGET_CFG)/$(LIB)
#OBJS = $(addprefix $(OBJDIR)/, $(CFILES:%.c=%.o))
OBJS = micasad-init
CUR_DIR := $(shell pwd)
all: $(OBJDIR)/$(MODULE_NAME)
#
# Pattern based rules.
#
vpath %.c $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
vpath %.cpp $(PLATFORMDEPENDENTSOURCEDIR) $(PLATFORMINDEPENDENTSOURCEDIR)
$(OBJS):
@echo [======== Compiling $@ ========]
@echo [======== OBJDIR $(OBJDIR) ========]
$(CC) -o $@ $(CFILES)
$(OBJDIR)/$(MODULE_NAME): $(OBJDIR) $(OBJS)
cp -f $(OBJS) $(OBJDIR)/$(MODULE_NAME)
cp -f $(OBJDIR)/$(MODULE_NAME) $(CASABINDIR)/$(TARGET_CFG)/$(MODULE_NAME)
$(OBJDIR):
[ -d $(OBJDIR) ] || mkdir -p $(OBJDIR)
[ -d $(CASABINDIR) ] || mkdir -p $(CASABINDIR)
[ -d $(CASABINDIR)/$(TARGET_CFG) ] || mkdir -p $(CASABINDIR)/$(TARGET_CFG)
install-exec-local: $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
$(mkinstalldirs) $(DESTDIR)$(libdir)
$(INSTALL_PROGRAM) $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT) $(DESTDIR)$(libdir)/
uninstall-local:
cd $(DESTDIR)$(libdir); rm -f $(OBJDIR)/$(MODULE_NAME).$(MODULE_EXT)
rmdir $(DESTDIR)$(libdir)
#installcheck-local: install
# $(mkinstalldirs) $(DESTDIR)$(libdir)
# $(INSTALL_PROGRAM) $(DESTDIR)$(libdir)
# cd $(DESTDIR)$(libdir); $(MONO)
clean-local:
if [ -d $(TARGET_CFG) ]; then rm -rf $(TARGET_CFG); fi
distclean-local:
maintainer-clean-local:
rm -f Makefile.in

24
micasad/startup/casacfgpam Executable file
View File

@@ -0,0 +1,24 @@
#!/bin/bash
# Adding CASA pam entries to pam files.
rm -f *.rpmsave
for file in "/etc/pam.d/login" "/etc/pam.d/sshd" "/etc/pam.d/xdm" "/etc/pam.d/gdm" "/etc/pam.d/kdm"
do
if [ -f $file ]
then
sed -i '/pam_micasa/d' $file
var=`grep pam_unix2.so $file`
entry=`echo -e "auth\t required\tpam_micasa.so"`
if [ "$var" != "" ]
then
sed -i "/^auth.*required.*pam_unix2.so/a$entry" $file
continue
fi
var2=`grep common-auth $file`
if [ "$var2" != "" ]
then
sed -i "/^auth.*include.*common-auth/a$entry" $file
continue
fi
sed -i "0,/^auth/s/^\(auth.*\)/\1\n$entry/" $file
fi
done

View File

@@ -0,0 +1,10 @@
#!/bin/bash
# Remove the CASA pam entries from pam files.
for pam_file in "/etc/pam.d/login" "/etc/pam.d/sshd" "/etc/pam.d/xdm" "/etc/pam.d/gdm" "/etc/pam.d/kdm"
do
if [ -f $pam_file ]
then
sed -i '/pam_micasa/d' $pam_file
fi
done

12
micasad/startup/installcasa Executable file
View File

@@ -0,0 +1,12 @@
# enable the service
insserv -d /etc/init.d/micasad >/dev/null 2>&1
# install PAM modules
(/usr/sbin/casacfgpam)
RCODE=$?
if(test $RCODE != 0)
then
exit $RCODE
else
/etc/init.d/micasad restart >/dev/null 2>&1
exit 0
fi

18
micasad/startup/iscasaconfiged Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/bash
set -x
#
CFG=`rpm -qa |grep -i ^casa-[1-9]`
if [ "$CFG" != "" ]
then
PAM=`find /etc/pam.d -exec grep -i casa \{\} \;`
if [ "$PAM" != "" ]
then
exit 0
else
exit 1
fi
else
exit 1
fi

125
micasad/startup/micasad Normal file
View File

@@ -0,0 +1,125 @@
#! /bin/sh
#
### BEGIN INIT INFO
# Provides: micasad
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start: 1 2 3 5
# Default-Stop:
# Short-Description: miCASA daemon
# Description: miCASA daemon
### END INIT INFO
MICASAD_BIN=/usr/sbin/micasad.sh
test -x $MICASAD_BIN || exit 5
. /etc/rc.status
# Shell functions sourced from /etc/rc.status:
# rc_check check and set local and overall rc status
# rc_status check and set local and overall rc status
# rc_status -v ditto but be verbose in local rc status
# rc_status -v -r ditto and clear the local rc status
# rc_failed set local and overall rc status to failed
# rc_reset clear local rc status (overall remains)
# rc_exit exit appropriate to overall rc status
# First reset status of this service
rc_reset
function pid_exists()
{
test -f /var/run/micasad.pid 2> /dev/null
}
function process_running()
{
kill -0 `cat /var/run/micasad.pid` 2> /dev/null
}
function is_running()
{
pid_exists && process_running
}
case "$1" in
start)
if ! is_running; then \
echo -n "Starting miCASA daemon"
$MICASAD_BIN
fi
# Remember status and be verbose
rc_status -v
;;
stop)
if is_running; then \
echo -n "Shutting down miCASA daemon"
#killproc -TERM $MICASAD_BIN
pid=`cat /var/run/micasad.pid` >/dev/null 2>&1
kill -s TERM $pid >/dev/null 2>&1
fi
# Remember status and be verbose
rc_status -v
;;
try-restart|condrestart)
$0 status
if test $? = 0
then
$0 restart
else
rc_reset # Not running is not a failure.
fi
# Remember status and be quiet
rc_status
;;
restart)
## Stop the service and regardless of whether it was
## running or not, start it again.
echo "Restarting miCASA daemon"
$0 stop
$0 start
# Remember status and be quiet
rc_status
;;
reload)
## Stop the service and regardless of whether it was
## running or not, start it again.
echo "Restarting miCASA daemon"
$0 stop
$0 start
# Remember status and be quiet
rc_status
;;
force-reload)
## Stop the service and regardless of whether it was
## running or not, start it again.
echo "Restarting miCASA daemon"
$0 stop
$0 start
# Remember status and be quiet
rc_status
;;
status)
echo -n "Checking miCASA daemon"
if pid_exists && ! process_running 2> /dev/null; then \
rc_failed 1
elif ! pid_exists && ! process_running 2> /dev/null; then \
rc_failed 3
fi
rc_status -v
;;
*)
echo "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status}"
exit 1
;;
esac
rc_exit

View File

@@ -0,0 +1,39 @@
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[])
{
int no_fds = 0;
int fd = -1;
int rc = 0;
pid_t sid;
/*
* Fork a child process
* Exit parent
* Change directory to "/"
* Redirect stdin, stdout, stderr to "/dev/null"
*/
rc = daemon (0, 0);
if ( rc < 0 )
{
exit(EXIT_FAILURE);
}
/* Create a new session */
setsid();
/* Set the file mode creation mask */
umask(022);
/* Close the associated standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Start micasad */
return execv ("/usr/bin/mono", argv);
}

View File

@@ -0,0 +1,11 @@
#!/bin/sh
HOST_ARCH=`uname -a | grep -c x86_64`
if [ $HOST_ARCH -gt 0 ]
then ARCH_LIB=64
else
ARCH_LIB=
fi
export MONO_PATH=/usr/lib$ARCH_LIB/
exec /usr/bin/micasad-init /usr/bin/micasad.exe

12
micasad/startup/uninstallcasa Executable file
View File

@@ -0,0 +1,12 @@
#disable the service
/etc/init.d/micasad stop >/dev/null 2>&1
insserv -r /etc/init.d/micasad >/dev/null 2>&1
# uninstall PAM modules
(/usr/sbin/casaucfgpam)
RCODE=$?
if(test $RCODE != 0)
then
exit $RCODE
else
exit 0
fi

14
micasad/test/ReadMe.txt Normal file
View File

@@ -0,0 +1,14 @@
Read Me:
-------
The current Directoy "test" is has unit test cases to test the miCASA daemon c# code.
It uses Nunit(nunit.org) to develop testcases and execute the same.
There is a directory structure similar to the daemon code inside the test dir.
For any function or aspect which needs to be tested in Daemon, add Test code here and
the Test stubs will appear in the Ddebug build of micasad.exe
usage mono /dependencies/nunit-console.exe ../../bin/lux/dbg/micasad.exe
Windows has a GUI tool, can be downloaded at nunit.org

145
micasad/test/cache/TestKeyChain.cs vendored Normal file
View File

@@ -0,0 +1,145 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
namespace sscs.cache
{
[TestFixture]
public class TestKeyChain
{
Secret mysec;
KeyChain mykc;
string secval;
byte[] secbyte;
[SetUp]
public void Init()
{
mykc = new KeyChain("TestingID");
secval= "novell123";
secbyte = Encoding.ASCII.GetBytes(secval);
mysec = new Secret();
mysec.SetKey("testkey");
mysec.SetValue(secbyte);
}
[Test]
public void TestAddSecret()
{
mykc.AddSecret(mysec);
Secret returnsecret = mykc.GetSecret("testkey");
Assert.AreEqual("novell123", Encoding.ASCII.GetString(returnsecret.GetValue("testkey")));
}
[Test]
public void TestAddSecretWithDup()
{
//Add one more with same secret id
byte[] newvalue = Encoding.ASCII.GetBytes("miCASA");
mysec.SetValue(newvalue);
mykc.AddSecret(mysec);
Secret returnsecret = mykc.GetSecret("testkey");
Assert.AreEqual("miCASA", Encoding.ASCII.GetString(returnsecret.GetValue("testkey")));
}
[Test]
[ExpectedException(typeof(SecretNotFoundException))]
public void TestRemoveSecret()
{
mykc.RemoveSecret("testkey");
//Try and get the same.
//Secret sec = mykc.GetSecret("testkey");
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void TestGetAllSecretsWhenNone()
{
// IDictionaryEnumerator myenum = (IDictionaryEnumerator)mykc.GetAllSecrets();
//Object temp = myenum.Current;
}
[Test]
public void TestGetAllSecrets()
{
int count = 0;
byte[] val1 = Encoding.ASCII.GetBytes("val1");
byte[] val2 = Encoding.ASCII.GetBytes("val2");
byte[] val3 = Encoding.ASCII.GetBytes("val3");
Secret sec1 = new Secret("key1", val1);
Secret sec2 = new Secret("key2", val2);
Secret sec3 = new Secret("key3", val3);
mykc.AddSecret(sec1);
mykc.AddSecret(sec2);
mykc.AddSecret(sec3);
IDictionaryEnumerator myenum =(IDictionaryEnumerator) mykc.GetAllSecrets();
while(myenum.MoveNext())
{
count++;
}
Assert.AreEqual(3, mykc.GetNumSecrets());
Assert.AreEqual(3, count);
}
}
}
#endif

77
micasad/test/cache/TestSecret.cs vendored Normal file
View File

@@ -0,0 +1,77 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using NUnit.Framework;
namespace sscs.cache
{
[TestFixture]
public class TestSecret
{
[Test]
public void DefaultAddSecret()
{
string someotherstr = "newvalue";
byte[] newval = Encoding.ASCII.GetBytes(someotherstr);
Secret mysec = new Secret();
mysec.SetKey("newkey");
mysec.SetValue(newval);
mysec.SetEpasswd("enhanced");
mysec.SetKey("alternatekey");
Assert.AreEqual("newvalue", Encoding.ASCII.GetString(mysec.GetValue("alternatekey")));
}
[Test]
public void TestAddSecret()
{
string somestr = "novell123";
string someotherstr = "newvalue";
byte[] mybyte = Encoding.ASCII.GetBytes(somestr);
byte[] newval = Encoding.ASCII.GetBytes(someotherstr);
Secret mysec = new Secret("mail", mybyte);
mysec.SetKey("newkey");
mysec.SetValue(newval);
Assert.AreEqual("newkey", mysec.GetKey());
Assert.AreEqual("newvalue", Encoding.ASCII.GetString(mysec.GetValue()));
}
//TBD: Need to Add Timestamp related cases, could be done when we use it
}
}
#endif

150
micasad/test/cache/TestSecretStore.cs vendored Normal file
View File

@@ -0,0 +1,150 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
namespace sscs.cache
{
[TestFixture]
public class TestSecretStore
{
User theuser = null;
UnixUserIdentifier UserId = null;
SecretStore mysec = null;
KeyChain mykc = null;
byte[] secbyte = null;
Secret mysecret = null;
[SetUp]
public void Init()
{
mykc = new KeyChain("TestingID");
mysecret = new Secret();
mysecret.SetKey("testkey");
secbyte = Encoding.ASCII.GetBytes("NOVELL");
mysecret.SetValue(secbyte);
mykc.AddSecret(mysecret);
UserId = new UnixUserIdentifier(420);
theuser = new UnixUser(UserId);
mysec = new SecretStore(theuser);
}
[Test]
public void TestIntialState()
{
Assert.AreEqual(0, mysec.GetNumKeyChains());
// Assert.AreEqual(0, mysec.getRefCount());
Assert.AreEqual(0, mysec.GetSecretStoreState());
}
[Test]
public void TestAddKeyChain()
{
mysec.AddKeyChain(mykc);
Assert.AreEqual(1, mysec.GetNumKeyChains());
Secret returnsec = (mysec.GetKeyChain("TestingID")).GetSecret("testkey");;
Assert.AreEqual("NOVELL", Encoding.ASCII.GetString(returnsec.GetValue("testkey")));
}
[Test]
public void TestRemoveKeyChain()
{
mysec.RemoveKeyChain("TestingID");
Assert.AreEqual(0, mysec.GetNumKeyChains());
Assert.AreEqual(false, mysec.CheckIfKeyChainExists("TestingID"));
}
[Test]
[ExpectedException(typeof(KeyChainDoesNotExistException))]
public void TestRemoveKeyChainAgain()
{
mysec.GetKeyChain("TestingID");
}
[Test]
public void TestGetKeyChainEnumerator()
{
KeyChain mykc1 = new KeyChain("kc1");
KeyChain mykc2 = new KeyChain("kc2");
KeyChain mykc3 = new KeyChain("kc3");
Secret mysecret1 = new Secret("key1", secbyte);
Secret mysecret2 = new Secret("key2", secbyte);
Secret mysecret3 = new Secret("key3", secbyte);
mykc1.AddSecret(mysecret1);
mykc2.AddSecret(mysecret2);
mykc3.AddSecret(mysecret3);
mysec.AddKeyChain(mykc1);
mysec.AddKeyChain(mykc2);
mysec.AddKeyChain(mykc3);
Assert.AreEqual(3, mysec.GetNumKeyChains());
}
}
}
#endif

View File

@@ -0,0 +1,110 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.verbs;
namespace sscs.cache
{
[TestFixture]
public class TestRequestParser
{
RequestParser reqParser = null;
[SetUp]
public void Init()
{
reqParser = new RequestParser();
}
[Test]
[ExpectedException(typeof(FormatException))]
public void TestNullRequest()
{
// SSVerb verb = reqParser.ParseRequest(null);
reqParser.ParseRequest(null);
}
[Test]
public void TestParseRequest()
{
// byte[] buf = new byte[1024];
//buf[0] = 1;
// buf[1] = 1;
int i =1;
byte[] dummy = BitConverter.GetBytes(i);
SSVerb verb = reqParser.ParseRequest(dummy);
Assert.AreEqual("sscs.verbs.OpenSecretStore", verb.GetVerbName());
i = 18;
dummy = BitConverter.GetBytes(i);
verb = reqParser.ParseRequest(dummy);
Assert.AreEqual("sscs.verbs.GetUserState", verb.GetVerbName());
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void TestParseRequestInvalid()
{
byte[] buf = new byte[1024] ;
buf[0] = 25;
buf[1] = 25;
// SSVerb verb = reqParser.ParseRequest(buf);
reqParser.ParseRequest(buf);
}
}
}
#endif

View File

@@ -0,0 +1,176 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
namespace sscs.common
{
[TestFixture]
public class TestSessionManager
{
User theuser = null;
UnixUserIdentifier UserId = null;
UnixUserIdentifier root = null;
SecretStore mysec = null;
SecretStore anothersec = null;
KeyChain mykc1 = null;
KeyChain mykc2 = null;
byte[] secbyte1 = null;
byte[] secbyte2 = null;
Secret mysecret1 = null;
Secret mysecret2 = null;
SessionManager sesman ;
[SetUp]
public void Init()
{
sesman = SessionManager.GetSessionManager;
mykc1 = new KeyChain("k1");
mykc2 = new KeyChain("k2");
mysecret1 = new Secret();
mysecret2 = new Secret();
mysecret1.SetKey("key1");
mysecret2.SetKey("key2");
secbyte1 = Encoding.ASCII.GetBytes("NOVELL");
secbyte2 = Encoding.ASCII.GetBytes("IBM");
mysecret1.SetValue(secbyte1);
mysecret2.SetValue(secbyte2);
mykc1.AddSecret(mysecret1);
mykc2.AddSecret(mysecret2);
UserId = new UnixUserIdentifier(420);
root = new UnixUserIdentifier(0);
//theuser = new UnixUser(UserId);
}
[Test]
public void TestCreateUserSession()
{
anothersec = SessionManager.CreateUserSession(root);
mysec = SessionManager.CreateUserSession(UserId);
//Assert.AreEqual(1, mysec.getRefCount());
//Assert.AreEqual(1, anothersec.getRefCount());
Assert.AreEqual(true, SessionManager.CheckIfUserSessionExists(UserId));
Assert.AreEqual(true, SessionManager.CheckIfUserSessionExists(root));
}
[Test]
public void TestAddtoSession()
{
SecretStore s1 = SessionManager.GetUserSecretStore(UserId);
SecretStore s2 = SessionManager.GetUserSecretStore(root);
s1.AddKeyChain(mykc1);
s2.AddKeyChain(mykc2);
s1 = SessionManager.GetUserSecretStore(UserId);
s2 = SessionManager.GetUserSecretStore(root);
KeyChain returnK1 = s1.GetKeyChain("k1");
Secret returnS1 = returnK1.GetSecret("key1");
KeyChain returnK2 = s2.GetKeyChain("k2");
Secret returnS2 = returnK2.GetSecret("key2");
Assert.AreEqual("NOVELL", Encoding.ASCII.GetString(returnS1.GetValue()));
Assert.AreEqual("IBM",Encoding.ASCII.GetString(returnS2.GetValue()) );
}
[Test]
[ExpectedException(typeof(KeyChainDoesNotExistException))]
public void TestInvalidAccess()
{
SecretStore s1 = SessionManager.GetUserSecretStore(UserId);
//SecretStore s2 = SessionManager.GetUserSecretStore(root);
s1.GetKeyChain("k2");
}
[Test]
public void TestRemoveUserSession()
{
SessionManager.RemoveUserSession(UserId, true);
Assert.AreEqual(false, SessionManager.CheckIfUserSessionExists(UserId));
//TBD :Make the ref count more than one and delete call remove sesison once.
//The call it once more.. only second time it should remove the session entry.
}
}
}
#endif

View File

@@ -0,0 +1,79 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.IO;
using System.Threading;
using NUnit.Framework;
using sscs.communication;
namespace sscs.communication
{
[TestFixture]
public class TestUnixCommunication
{
static Communication comm;
Thread listeningthread = null;
[SetUp]
public void Init()
{
}
[Test]
//[Ignore("That thread thing")]
public void TestCommunication()
{
comm = new UnixCommunication();
listeningthread = new Thread(new ThreadStart(StartServ));
listeningthread.Start();
//comm.StartCommunicationEndPoint();
comm.CloseCommunicationEndPoint();
Assert.AreEqual(false, File.Exists("/tmp/novellSSCS"));
}
private static void StartServ()
{
comm.StartCommunicationEndPoint();
}
}
}
#endif

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,69 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestAddKeyChain
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,65 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestCloseSecretStore
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,68 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestEnumerateKeyChainID
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,69 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestEnumerateSecID
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,84 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestOpenSecretStore
{
[SetUp]
public void Init()
{
}
/*
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void TestNullVerb()
{
SSVerb verb = new OpenSecretStore();
verb.processRequest(UserId);
}
*/
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,69 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestReadSecret
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,70 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestRemoveKeyChain
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,71 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
#if DEBUG
using System;
using System.Text;
using System.Collections;
//using System.InvalidOperationException;
using NUnit.Framework;
using sscs.common;
using sscs.cache;
using sscs.verbs;
namespace sscs.verbs
{
[TestFixture]
public class TestWriteSecret
{
[SetUp]
public void Init()
{
}
// TBD: Need to construct the input buf and output buf and call the processRequest()
//As of now all internal functions are tested and the cachelib test code
// also indirectly tests this function.
}
}
#endif

View File

@@ -0,0 +1,151 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.common;
using sscs.cache;
using sscs.constants;
namespace sscs.verbs
{
/*
* This class is implementation of AddKeyChain call.
* There will be one instance existing for every call made by the client.
*/
internal class AddKeyChain : SSVerb
{
private ushort msgId = 0;
private uint inMsgLen = 0;
private uint keyChainFlags = 0;
private uint keyChainIdLen = 0;
private string keyChainId;
private uint outMsgLen = 0;
private byte[] inBuf;
private byte[] outBuf;
private int retCode = 0;
/*
* This method sets the class member with the byte array received.
*/
public void SetMessageContent(byte[] ipcBytes)
{
CSSSLogger.ExecutionTrace(this);
inBuf = ipcBytes;
}
/*
* This method does the actual implementation of AddKeyChain
*/
public byte[] ProcessRequest(UserIdentifier userId)
{
/* If an exception occurs in message format decoding,
* it is handled by AppHandler
*/
CSSSLogger.ExecutionTrace(this);
// Message Format decipher - Start
msgId = BitConverter.ToUInt16(inBuf,0);
inMsgLen = BitConverter.ToUInt32(inBuf,2);
if( inMsgLen != inBuf.Length )
throw new FormatException(" MsgLen sent does not match the length of the message received.");
keyChainFlags = BitConverter.ToUInt32(inBuf,6);
keyChainIdLen = BitConverter.ToUInt32(inBuf,10);
byte[] tempArr = new byte[keyChainIdLen];
Array.Copy(inBuf,14,tempArr,0,keyChainIdLen);
keyChainId = Encoding.UTF8.GetString(tempArr);
// Message Format decipher - End
try
{
SecretStore ssStore = null;
KeyChain keyChain = null;
keyChain = new KeyChain(keyChainId);
ssStore = SessionManager.GetUserSecretStore(userId);
if( ssStore.CheckIfKeyChainExists(keyChainId) == false )
{
ssStore.AddKeyChain(keyChain);
}
else
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Keychain already present for keychain id " +keyChainId );
retCode = IPCRetCodes.SSCS_E_KEYCHAIN_ALREADY_EXISTS;
}
}
catch(UserNotInSessionException)
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Unable to get user's secretstore" );
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
try
{
msgId = 5;
outMsgLen = 10;
outBuf = new byte[10];
byte[] t = new byte[10];
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,outBuf,0,2);
t = BitConverter.GetBytes((uint)outMsgLen);
Array.Copy(t,0,outBuf,2,4);
t = BitConverter.GetBytes(retCode);
Array.Copy(t,0,outBuf,6,4);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new FormatException("Unable to form the response " + e.ToString());
}
return outBuf;
}
/*
* Gives the name of operation performed. Will be used in case
* of error.
*/
public string GetVerbName()
{
CSSSLogger.ExecutionTrace(this);
return (this.ToString());
}
}
}

View File

@@ -0,0 +1,139 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.common;
using sscs.cache;
using sscs.constants;
namespace sscs.verbs
{
/*
* This class is implementation of CloseSecretStore call.
* There will be one instance existing for every call made by the client.
*/
internal class CloseSecretStore : SSVerb
{
private ushort msgId = 0;
private uint inMsgLen = 0;
private uint outMsgLen = 0;
private byte[] inBuf;
private byte[] outBuf;
private int retCode = 0;
/*
* This method sets the class member with the byte array received.
*/
public void SetMessageContent(byte[] ipcBytes)
{
CSSSLogger.ExecutionTrace(this);
inBuf = ipcBytes;
}
/*
* This method does the actual implementation of CloseSecretStore
*
*/
public byte[] ProcessRequest(UserIdentifier userId)
{
/* If an exception occurs in message format decoding,
* it is handled by AppHandler
*/
CSSSLogger.ExecutionTrace(this);
// Message Format decipher - Start
msgId = BitConverter.ToUInt16(inBuf,0);
inMsgLen = BitConverter.ToUInt32(inBuf,2);
if( inMsgLen != inBuf.Length )
throw new FormatException(" MsgLen sent does not match the length of the message received.");
uint ssFlags = BitConverter.ToUInt32(inBuf,6);
// Message Format decipher - End
try
{
if ((ssFlags & ConstFlags.SSFLAGS_DESTROY_SESSION_F) == ConstFlags.SSFLAGS_DESTROY_SESSION_F)
{
#if W32
SessionManager.RemoveUserSession(userId, true);
#else
SessionManager.CheckAndDestroySession(userId, true);
#endif
}
else
SessionManager.RemoveUserSession(userId, false);
}
catch(Exception)
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Exception encountered in removing user session.");
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
// Construct a Reply.
try
{
msgId = 2;
outMsgLen = 10;
outBuf = new byte[10];
byte[] t = new byte[10];
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,outBuf,0,2);
t = BitConverter.GetBytes((uint)outMsgLen);
Array.Copy(t,0,outBuf,2,4);
t = BitConverter.GetBytes(retCode);
Array.Copy(t,0,outBuf,6,4);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new FormatException("Unable to form the response " + e.ToString());
}
return outBuf;
}
/*
* Gives the name of operation performed. Will be used in case
* of error.
*/
public string GetVerbName()
{
CSSSLogger.ExecutionTrace(this);
return this.ToString();
}
}
}

View File

@@ -0,0 +1,153 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.cache;
using sscs.common;
using sscs.constants;
namespace sscs.verbs
{
/*
* This class is implementation of EnumerateKeyChainIds call.
* There will be one instance existing for every call made by the client.
*/
internal class EnumerateKeyChainIds : SSVerb
{
private ushort msgId = 0;
private uint inMsgLen = 0;
private uint outMsgLen = 0;
private int retCode = 0;
private byte[] inBuf;
private byte[] outBuf;
/*
* This method sets the class member with the byte array received.
*/
public void SetMessageContent(byte[] ipcBytes)
{
CSSSLogger.ExecutionTrace(this);
inBuf = ipcBytes;
}
/*
* This method does the actual implementation of EnumerateKeyChainIds
*
*/
public byte[] ProcessRequest(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(this);
int keyChainIdsLen = 0;
StringBuilder keyChainIds = new StringBuilder();
/* If an exception occurs in message format decoding,
* it is handled by AppHandler
*/
// Message Format decipher - Start
msgId = BitConverter.ToUInt16(inBuf,0);
inMsgLen = BitConverter.ToUInt32(inBuf,2);
if( inMsgLen != inBuf.Length )
throw new FormatException(" MsgLen sent does not match the length of the message received.");
// Message Format decipher - End
try
{
int index = 0;
SecretStore ssStore = SessionManager.GetUserSecretStore(userId);
int numKeyChains = ssStore.GetNumKeyChains();
IDictionaryEnumerator etor = (IDictionaryEnumerator)ssStore.GetKeyChainEnumerator();
while(etor.MoveNext())
{
index++;
keyChainIds.Append((string)etor.Key,0,(((string)(etor.Key)).Length)-1);
keyChainIdsLen += ((string)(etor.Key)).Length-1;
if( index != numKeyChains )
{
keyChainIds.Append("*");
keyChainIdsLen += 1;
}
}
}
catch(UserNotInSessionException)
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Unable to get user's secretstore" );
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
// Construct a Reply.
try
{
msgId = 4;
outMsgLen = 14 + (uint)keyChainIds.Length;
outBuf = new byte[outMsgLen];
byte[] t = new byte[10];
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,outBuf,0,2);
t = BitConverter.GetBytes((uint)outMsgLen);
Array.Copy(t,0,outBuf,2,4);
t = BitConverter.GetBytes(keyChainIdsLen);
Array.Copy(t,0,outBuf,6,4);
Encoding.UTF8.GetBytes(keyChainIds.ToString(),0,keyChainIds.Length,outBuf,10);
t = BitConverter.GetBytes(retCode);
Array.Copy(t,0,outBuf,(10+keyChainIds.Length),4);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new FormatException("Unable to form the response " + e.ToString());
}
return outBuf;
}
/*
* Gives the name of operation performed. Will be used in case
* of error.
*/
public string GetVerbName()
{
return this.ToString();
}
}
}

View File

@@ -0,0 +1,169 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.cache;
using sscs.common;
using sscs.constants;
namespace sscs.verbs
{
/*
* This class is implementation of EnumerateSecretIds call.
* There will be one instance existing for every call made by the client.
*/
internal class EnumerateSecretIds : SSVerb
{
private ushort msgId = 0;
private uint inMsgLen = 0;
private uint outMsgLen = 0;
private uint keyChainIdLen = 0;
private string keyChainId;
private int retCode = 0;
private byte[] inBuf;
private byte[] outBuf;
/*
* This method sets the class member with the byte array received.
*/
public void SetMessageContent(byte[] ipcBytes)
{
CSSSLogger.ExecutionTrace(this);
inBuf = ipcBytes;
}
/*
* This method does the actual implementation of EnumerateSecretIds
*
*/
public byte[] ProcessRequest(UserIdentifier userId)
{
/* If an exception occurs in message format decoding,
* it is handled by AppHandler
*/
int secretIdsLen = 0;
StringBuilder secretIds = new StringBuilder();
// Message Format decipher - Start
msgId = BitConverter.ToUInt16(inBuf,0);
inMsgLen = BitConverter.ToUInt32(inBuf,2);
if( inMsgLen != inBuf.Length )
throw new FormatException(" MsgLen sent does not match the length of the message received.");
keyChainIdLen = BitConverter.ToUInt32(inBuf,6);
byte[] keyChainIdArr = new byte[keyChainIdLen];
Array.Copy(inBuf,10,keyChainIdArr,0,keyChainIdLen);
keyChainId = Encoding.UTF8.GetString(keyChainIdArr);
// Message Format decipher - End
try
{
SecretStore ssStore = SessionManager.GetUserSecretStore(userId);
if( ssStore.CheckIfKeyChainExists(keyChainId) )
{
KeyChain keyChain = ssStore.GetKeyChain(keyChainId);
int numSecrets = keyChain.GetNumSecrets();
int index = 0;
IDictionaryEnumerator etor = (IDictionaryEnumerator)keyChain.GetAllSecrets();
while(etor.MoveNext())
{
index++;
secretIds.Append((string)etor.Key,0,(((string)(etor.Key)).Length)-1);
secretIdsLen += ((string)(etor.Key)).Length-1;
if( index != numSecrets )
{
secretIds.Append("*");
secretIdsLen += 1;
}
}
}
else
{
retCode = IPCRetCodes.SSCS_E_KEYCHAIN_DOES_NOT_EXIST;
}
}
catch(UserNotInSessionException)
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Unable to get user's secretstore" );
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
catch(Exception)
{
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
//Construct a reply.
try
{
msgId = 7;
outMsgLen = 14 + (uint)secretIds.Length;
outBuf = new byte[outMsgLen];
byte[] t = new byte[10];
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,outBuf,0,2);
t = BitConverter.GetBytes((uint)outMsgLen);
Array.Copy(t,0,outBuf,2,4);
t = BitConverter.GetBytes(secretIdsLen);
Array.Copy(t,0,outBuf,6,4);
Encoding.UTF8.GetBytes(secretIds.ToString(),0,secretIds.Length,outBuf,10);
t = BitConverter.GetBytes(retCode);
Array.Copy(t,0,outBuf,(10+secretIds.Length),4);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new FormatException("Unable to form the response " + e.ToString());
}
return outBuf;
}
/*
* Gives the name of operation performed. Will be used in case
* of error.
*/
public string GetVerbName()
{
CSSSLogger.ExecutionTrace(this);
return this.ToString();
}
}
}

View File

@@ -0,0 +1,142 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.common;
using sscs.cache;
using sscs.constants;
namespace sscs.verbs
{
/*
* This class is implementation of GetSecretStoreInfo call.
* There will be one instance existing for every call made by the client.
*/
internal class GetSecretStoreInfo : SSVerb
{
private ushort msgId = 0;
private uint inMsgLen = 0;
private uint outMsgLen = 0;
private uint numKeyChains = 0;
private byte[] inBuf;
private byte[] outBuf;
private int retCode = 0;
/*
* This method sets the class member with the byte array received.
*/
public void SetMessageContent(byte[] ipcBytes)
{
CSSSLogger.ExecutionTrace(this);
inBuf = ipcBytes;
}
/*
* This method does the actual implementation of GetSecretStoreInfo
*
*/
public byte[] ProcessRequest(UserIdentifier userId)
{
CSSSLogger.ExecutionTrace(this);
/* If an exception occurs in message format decoding,
* it is handled by AppHandler
*/
// Message Format decipher - Start
msgId = BitConverter.ToUInt16(inBuf,0);
inMsgLen = BitConverter.ToUInt32(inBuf,2);
if( inMsgLen != inBuf.Length )
throw new FormatException(" MsgLen sent does not match the length of the message received.");
// Message Format decipher - End
try
{
SecretStore ssStore = SessionManager.GetUserSecretStore(userId);
numKeyChains = (uint) ssStore.GetNumKeyChains();
}
catch(UserNotInSessionException)
{
CSSSLogger.DbgLog("In " + CSSSLogger.GetExecutionPath(this) + " Unable to get user's secretstore" );
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
retCode = IPCRetCodes.SSCS_E_SYSTEM_ERROR;
}
// Construct Response
try
{
msgId = 11;
outMsgLen = 14;
outBuf = new byte[outMsgLen];
byte[] t = new byte[10];
t = BitConverter.GetBytes((ushort)msgId);
Array.Copy(t,0,outBuf,0,2);
t = BitConverter.GetBytes((uint)outMsgLen);
Array.Copy(t,0,outBuf,2,4);
t = BitConverter.GetBytes(numKeyChains);
Array.Copy(t,0,outBuf,6,4);
t = BitConverter.GetBytes(retCode);
Array.Copy(t,0,outBuf,10,4);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
throw new FormatException("Unable to form the response " + e.ToString());
}
return outBuf;
}
/*
* Gives the name of operation performed. Will be used in case
* of error.
*/
public string GetVerbName()
{
CSSSLogger.ExecutionTrace(this);
return this.ToString();
}
}
}

56
micasad/verbs/ISSVerb.cs Normal file
View File

@@ -0,0 +1,56 @@
/***********************************************************************
*
* Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail,
* you may find current contact information at www.novell.com.
*
***********************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Threading;
using sscs.verbs;
using sscs.common;
namespace sscs.verbs
{
/*
* Defines the interfaces to be implemenetd by all Secret Store Verbs.
*/
interface SSVerb
{
/* Takes in the raw bytes and sets them for a Verb,
* so that the verb will execute in the bytes given.
* TBD: In case we are able to send the byte[] through constructor,
* we can avoid this interface.
*/
void SetMessageContent(byte[] rawbytes);
/* Takes in the SecretStore Reeference and returns the correct SSVerb
*/
byte[] ProcessRequest(UserIdentifier userId);
//Gives the name of operation performed.Can be used in case of error.
string GetVerbName();
}
}

Some files were not shown because too many files have changed in this diff Show More