Patches sent by India based on Security review.

This commit is contained in:
Jim Norman 2006-04-06 20:09:26 +00:00
parent 861619e231
commit b2b5903126
7 changed files with 816 additions and 686 deletions

View File

@ -20,247 +20,253 @@
*
***********************************************************************/
#include "sscs_ipc.h"
#ifdef SSCS_WIN32_PLAT_F
#include "windows.h"
#define XTIER_RPC_PIPE TEXT("\\\\.\\PIPE\\SS_RPC_PIPE")
// global
int firstReadAfterWrite = 0;
#endif
/*
*/
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_create()
{
int retVal = 0;
struct sockaddr_un servAddr;
char path[MAX_SOCKET_PATH_LEN];
int sockFd = 0;
do
{
sockFd = socket(AF_UNIX,SOCK_STREAM,0);
if( sockFd < 0 )
{
retVal = sockFd;
break;
}
memset(&servAddr,0,sizeof(servAddr));
servAddr.sun_family = AF_UNIX;
strcpy(servAddr.sun_path,"/tmp/.novellCASA");
retVal = connect(sockFd,(struct sockaddr*)&servAddr, sizeof(servAddr));
if(retVal < 0 )
{
DMSG(("Connect fails : %s\n",strerror(errno)));
DMSG(("Closing socket : %d\n",sockFd));
close(sockFd);
break;
}
else
retVal = sockFd;
}while(0);
return retVal;
}
#else
void * ipc_win_create()
{
//#ifdef SSCS_WIN32_PLAT_F
// connect to the named Pipe
HANDLE hPipe = NULL;
int rcode;
DWORD mode = PIPE_READMODE_MESSAGE;
hPipe = CreateFile(
XTIER_RPC_PIPE,
GENERIC_READ | GENERIC_WRITE,
0,
NULL, //null,
OPEN_EXISTING,
0,
0);
if (hPipe == INVALID_HANDLE_VALUE)
{
rcode = GetLastError();
return 0;
}
return hPipe;
}
#endif
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_write(int fd, Byte *pData, int bytes)
{
int retVal = write(fd,pData,bytes);
if( retVal < 0 )
{
DMSG(("Write returns error : %d - %s\n",retVal, strerror(errno)));
}
return retVal;
//#endif
}
#else
int ipc_win_write(HANDLE hPipe, LPCVOID lpBuffer, DWORD bytesToWrite)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
int icode;
DWORD lpBytesWritten = 0;
//LPCVOID msgLen = malloc(4);
// rcode = WaitNamedPipe(
// XTIER_RPC_PIPE,
// NMPWAIT_WAIT_FOREVER);
// the server expects us to first write the number of bytes in the msg we're about to write.
rcode = WriteFile(
hPipe,
(LPCVOID)&bytesToWrite,
4,
&lpBytesWritten,
NULL);
if (!rcode)
{
icode = GetLastError();
return 0;
}
// rcode = WaitNamedPipe(
// XTIER_RPC_PIPE,
// NMPWAIT_WAIT_FOREVER);
rcode = WriteFile(
hPipe,
lpBuffer, //LPCVOID lpBuffer,
bytesToWrite, //DWORD nNumberOfBytesToWrite,
&lpBytesWritten, // LPDWORD lpNumberOfBytesWritten,
NULL); //LPOVERLAPPED lpOverlapped
if (!rcode)
{
icode = GetLastError();
}
firstReadAfterWrite = 1;
return lpBytesWritten;
}
#endif
/*
*
*/
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_read(int fd, Byte *pData, int bytes)
{
int bytesToRead = 0; // Keep track of number of bytes to read
int bytesRead = 0; // Number of bytes read
int retVal = 0;
for(bytesToRead = bytes; bytesToRead;)
{
bytesRead = read(fd, pData, bytesToRead);
if(bytesRead < 0)
{
return -1;
}
bytesToRead -= bytesRead;
pData += bytesRead;
}
return bytesRead;
}
//#endif
#else
int ipc_win_read(HANDLE hPipe, LPVOID lpBuffer, DWORD numOfBytesToRead)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
DWORD numBytesRead = 0;
LPVOID pMsgLen = malloc(4);
int icode;
if (firstReadAfterWrite)
{
firstReadAfterWrite = 0;
// server first sends the number of bytes that gets sent.
rcode = ReadFile(
hPipe, //HANDLE hFile,
pMsgLen, //LPVOID lpBuffer,
4, //numOfBytesToRead, //DWORD nNumberOfBytesToRead,
&numBytesRead, //LPDWORD lpNumberOfBytesRead,
NULL); //LPOVERLAPPED lpOverlapped
if (!rcode)
{
icode = GetLastError();
return 0;
}
}
rcode = ReadFile(
hPipe, //HANDLE hFile,
lpBuffer, //LPVOID lpBuffer,
numOfBytesToRead, //DWORD nNumberOfBytesToRead,
&numBytesRead, //LPDWORD lpNumberOfBytesRead,
NULL); //LPOVERLAPPED lpOverlapped
if (pMsgLen)
free(pMsgLen);
return numBytesRead;
}
#endif
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_close(int fd)
{
return close(fd);
}
#else
int ipc_win_close(HANDLE hPipe)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
rcode = DisconnectNamedPipe(hPipe);
rcode = CloseHandle(hPipe);
return 0;
}
#endif
#include "sscs_ipc.h"
#ifdef SSCS_WIN32_PLAT_F
#include "windows.h"
#define XTIER_RPC_PIPE TEXT("\\\\.\\PIPE\\SS_RPC_PIPE")
// global
int firstReadAfterWrite = 0;
#endif
/*
*/
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_create()
{
int retVal = 0;
struct sockaddr_un servAddr;
char path[MAX_SOCKET_PATH_LEN];
int sockFd = 0;
do
{
sockFd = socket(AF_UNIX,SOCK_STREAM,0);
if( sockFd < 0 )
{
retVal = sockFd;
break;
}
memset(&servAddr,0,sizeof(servAddr));
servAddr.sun_family = AF_UNIX;
strcpy(servAddr.sun_path,"/tmp/.novellCASA");
retVal = connect(sockFd,(struct sockaddr*)&servAddr, sizeof(servAddr));
if(retVal < 0 )
{
DMSG(("Connect fails : %s\n",strerror(errno)));
DMSG(("Closing socket : %d\n",sockFd));
close(sockFd);
break;
}
else
retVal = sockFd;
}while(0);
return retVal;
}
#else
void * ipc_win_create()
{
//#ifdef SSCS_WIN32_PLAT_F
// connect to the named Pipe
HANDLE hPipe = NULL;
int rcode;
DWORD mode = PIPE_READMODE_MESSAGE;
hPipe = CreateFile(
XTIER_RPC_PIPE,
GENERIC_READ | GENERIC_WRITE,
0,
NULL, //null,
OPEN_EXISTING,
0,
0);
if (hPipe == INVALID_HANDLE_VALUE)
{
rcode = GetLastError();
return 0;
}
return hPipe;
}
#endif
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_write(int fd, Byte *pData, int bytes)
{
int retVal = write(fd,pData,bytes);
if( retVal < 0 )
{
DMSG(("Write returns error : %d - %s\n",retVal, strerror(errno)));
}
return retVal;
//#endif
}
#else
int ipc_win_write(HANDLE hPipe, LPCVOID lpBuffer, DWORD bytesToWrite)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
int icode;
DWORD lpBytesWritten = 0;
//LPCVOID msgLen = malloc(4);
// rcode = WaitNamedPipe(
// XTIER_RPC_PIPE,
// NMPWAIT_WAIT_FOREVER);
// the server expects us to first write the number of bytes in the msg we're about to write.
rcode = WriteFile(
hPipe,
(LPCVOID)&bytesToWrite,
4,
&lpBytesWritten,
NULL);
if (!rcode)
{
icode = GetLastError();
return 0;
}
// rcode = WaitNamedPipe(
// XTIER_RPC_PIPE,
// NMPWAIT_WAIT_FOREVER);
rcode = WriteFile(
hPipe,
lpBuffer, //LPCVOID lpBuffer,
bytesToWrite, //DWORD nNumberOfBytesToWrite,
&lpBytesWritten, // LPDWORD lpNumberOfBytesWritten,
NULL); //LPOVERLAPPED lpOverlapped
if (!rcode)
{
icode = GetLastError();
}
firstReadAfterWrite = 1;
return lpBytesWritten;
}
#endif
/*
*
*/
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_read(int fd, Byte *pData, int bytes)
{
int bytesToRead = 0; // Keep track of number of bytes to read
int bytesRead = 0; // Number of bytes read
int retVal = 0;
for(bytesToRead = bytes; bytesToRead;)
{
if ((bytesRead = read(fd, pData, bytesToRead)) == 0)
{
break;
}
else
{
if(bytesRead < 0)
{
return -1;
}
bytesToRead -= bytesRead;
pData += bytesRead;
}
}
return bytesRead;
}
//#endif
#else
int ipc_win_read(HANDLE hPipe, LPVOID lpBuffer, DWORD numOfBytesToRead)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
DWORD numBytesRead = 0;
LPVOID pMsgLen = malloc(4);
int icode;
if (firstReadAfterWrite)
{
firstReadAfterWrite = 0;
// server first sends the number of bytes that gets sent.
rcode = ReadFile(
hPipe, //HANDLE hFile,
pMsgLen, //LPVOID lpBuffer,
4, //numOfBytesToRead, //DWORD nNumberOfBytesToRead,
&numBytesRead, //LPDWORD lpNumberOfBytesRead,
NULL); //LPOVERLAPPED lpOverlapped
if (!rcode)
{
icode = GetLastError();
return 0;
}
}
rcode = ReadFile(
hPipe, //HANDLE hFile,
lpBuffer, //LPVOID lpBuffer,
numOfBytesToRead, //DWORD nNumberOfBytesToRead,
&numBytesRead, //LPDWORD lpNumberOfBytesRead,
NULL); //LPOVERLAPPED lpOverlapped
if (pMsgLen)
free(pMsgLen);
return numBytesRead;
}
#endif
#ifdef SSCS_LINUX_PLAT_F
int ipc_unx_close(int fd)
{
return close(fd);
}
#else
int ipc_win_close(HANDLE hPipe)
{
//#ifdef SSCS_WIN32_PLAT_F
BOOL rcode;
rcode = DisconnectNamedPipe(hPipe);
rcode = CloseHandle(hPipe);
return 0;
}
#endif

View File

@ -21,133 +21,145 @@
***********************************************************************/
using System;
using System.Net;
using System.Net.Sockets;
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
{
listeningSocket.Bind(sockEndPoint);
listeningSocket.Listen(50);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
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();
}
}
}
}
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);
}
listeningSocket.Bind(sockEndPoint);
listeningSocket.Listen(50);
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
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

@ -20,205 +20,208 @@
*
***********************************************************************/
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();
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;
}
}
}
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

@ -48,9 +48,25 @@ namespace Novell.CASA.MiCasa.Communication
SocketType.Stream,
ProtocolType.IP );
if (mSocket == null) throw new Exception("could not get socket");
sockEndPoint = new UnixEndPoint(socketFileName);
mSocket.Connect(sockEndPoint);
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)

View File

@ -24,6 +24,9 @@ using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
#if LINUX
using Mono.Unix;
#endif
using sscs.common;
using sscs.constants;
@ -69,9 +72,7 @@ namespace sscs.crypto
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
#if LINUX
Mono.Unix.Native.Syscall.chmod(fileName,Mono.Unix.Native.FilePermissions.S_IRUSR | Mono.Unix.Native.FilePermissions.S_IWUSR);
#endif
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
@ -93,8 +94,8 @@ namespace sscs.crypto
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to store the generated key");
bRet = false;
}
if (csEncrypt != null)
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
@ -107,9 +108,15 @@ namespace sscs.crypto
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;
}
@ -138,7 +145,7 @@ namespace sscs.crypto
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
@ -150,10 +157,10 @@ namespace sscs.crypto
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Unable to get the stored key");
baSavedKey = null;
}
if (csDecrypt != null)
}
if (csDecrypt != null)
csDecrypt.Close();
if ( fsDecrypt != null )
@ -180,9 +187,7 @@ namespace sscs.crypto
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName, FileMode.Create);
#if LINUX
Mono.Unix.Native.Syscall.chmod(fileName,Mono.Unix.Native.FilePermissions.S_IRUSR | Mono.Unix.Native.FilePermissions.S_IWUSR);
#endif
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
@ -203,8 +208,8 @@ namespace sscs.crypto
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Encrypting and storing to file failed.");
}
if (csEncrypt != null)
}
if (csEncrypt != null)
csEncrypt.Close();
if( fsEncrypt != null )
fsEncrypt.Close();
@ -224,8 +229,13 @@ namespace sscs.crypto
//Get a decryptor that uses the same key and IV as the encryptor.
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
if(!File.Exists(fileName))
{
#if LINUX
UnixFileInfo fsTest = new UnixFileInfo (fileName);
if((fsTest == null) || !(fsTest.Exists) || fsTest.IsSymbolicLink)
#else
if(!File.Exists(fileName))
#endif
{
return null;
}
@ -235,14 +245,15 @@ namespace sscs.crypto
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];
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);
@ -257,13 +268,13 @@ namespace sscs.crypto
{
if(storedHash[i] != newHash[i])
{
CSSSLogger.DbgLog("Hash doesnot match");
CSSSLogger.DbgLog("Hash doesnot match");
csDecrypt.Close();
fsDecrypt.Close();
return null;
}
}
}
csDecrypt.Close();
fsDecrypt.Close();
return tmpEncrypt;
@ -271,10 +282,10 @@ namespace sscs.crypto
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
if (csDecrypt != null)
{
csDecrypt.Close();
}
if (csDecrypt != null)
{
csDecrypt.Close();
}
if( fsDecrypt != null )
{
@ -393,9 +404,7 @@ namespace sscs.crypto
//Encrypt the data to a file
fsEncrypt = new FileStream(fileName,FileMode.Create);
#if LINUX
Mono.Unix.Native.Syscall.chmod(fileName,Mono.Unix.Native.FilePermissions.S_IRUSR | Mono.Unix.Native.FilePermissions.S_IWUSR);
#endif
// make hidden
File.SetAttributes(fileName, FileAttributes.Hidden);
@ -405,17 +414,17 @@ namespace sscs.crypto
//Write all data to the crypto stream and flush it.
csEncrypt.Write(baMasterPasscode, 0, baMasterPasscode.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.FlushFinalBlock();
csEncrypt.Close();
fsEncrypt.Close();
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
if (csEncrypt != null)
{
csEncrypt.Close();
}
if (csEncrypt != null)
{
csEncrypt.Close();
}
if( fsEncrypt != null )
{
@ -437,10 +446,20 @@ namespace sscs.crypto
/* Get a decryptor that uses the same key and
* IV as the encryptor.
*/
RijndaelManaged myRijndael = new RijndaelManaged();
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform decryptor = myRijndael.CreateDecryptor(baKey,
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);
@ -584,11 +603,11 @@ namespace sscs.crypto
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Validation of passcode failed.");
}
return false;
}
}
}
CSSSLogger.ExpLog(e.ToString());
CSSSLogger.DbgLog("Validation of passcode failed.");
}
return false;
}
}
}

View File

@ -27,6 +27,9 @@ 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;
@ -60,7 +63,12 @@ namespace sscs.lss
private SecretStore userStore = null;
private int persistThreadSleepTime = 1000 * 60 * 5; //1000 * 30;
private Thread persistThread = null;
private Thread persistThread = null;
#if LINUX
Mono.Unix.UnixFileSystemInfo sockFileInfo;
Mono.Unix.UnixUserInfo sockFileOwner;
#endif
private static string LINUXID = "Unix";
@ -120,23 +128,59 @@ namespace sscs.lss
}
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();
if(!File.Exists(fileName))
{
// check for tmp file
if (File.Exists(fileName+".tmp"))
File.Move(fileName+".tmp", fileName);
else
return null;
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");
}
}
// delete tmp file if there
if (File.Exists(fileName+".tmp"))
File.Delete(fileName+".tmp");
byte[] baPasscode = null;
if (null != m_baGeneratedKey)
@ -235,7 +279,7 @@ namespace sscs.lss
{
attrColl = keyNode.Attributes;
string key;
try
try
{
key = (attrColl[XmlConsts.idAttr]).Value;
}
@ -427,28 +471,46 @@ namespace sscs.lss
byte[] key = CASACrypto.GetKeySetFromFile(m_baGeneratedKey, userStore.GetKeyFilePath());
string fileName = userStore.GetPersistenceFilePath();
// rename existing file
if(File.Exists(fileName))
{
if (File.Exists(fileName+".tmp"))
File.Delete(fileName+".tmp");
File.Move(fileName, fileName+".tmp");
}
CASACrypto.EncryptDataAndWriteToFile(ms1.ToArray(),key,fileName);
//remove temp
if(File.Exists(fileName+".tmp"))
{
File.Delete(fileName+".tmp");
}
}
catch(Exception e)
{
CSSSLogger.ExpLog(e.ToString());
}
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

@ -221,42 +221,50 @@ static int32_t sscsshs_GetNextSHSEntry
* Internal function that escapes delimited characters in a string.
*
*/
static void sscsshs_ChkEscapeString(SS_UTF8_T *entryBuf)
static void sscsshs_ChkEscapeString(SS_UTF8_T **entryBuf)
{ /* beginning of the call */
/* ########################## DECLARATIONS START HERE ######################### */
int len = 0, i, k = 0;
int len = 0, i, k = 0, tmplen = 0, escaped = 0;
SS_UTF8_T *tempBuf = NULL;
/* ############################## CODE STARTS HERE ############################ */
if(!(tempBuf = (SS_UTF8_T *)malloc(NSSCS_MAX_SECRET_BUF_LEN - SSCS_CRED_SET_LEN)))
len = sscs_Utf8Strlen(*entryBuf) + 1;
if (len > (NSSCS_MAX_SECRET_BUF_LEN - SSCS_CRED_SET_LEN))
return;
/* We assume that all the chars in entryBuf might need escaping */
if(!(tempBuf = (SS_UTF8_T *)malloc(2 * (NSSCS_MAX_SECRET_BUF_LEN - SSCS_CRED_SET_LEN))))
{
return;
}
memset(tempBuf, 0, NSSCS_MAX_SECRET_BUF_LEN - SSCS_CRED_SET_LEN);
len = sscs_Utf8Strlen(entryBuf) + 1;
memset(tempBuf, 0, 2 * (NSSCS_MAX_SECRET_BUF_LEN - SSCS_CRED_SET_LEN));
for(i = 0; i < len; i++)
{
SS_UTF8_T c = entryBuf[i];
SS_UTF8_T c = *((*entryBuf)+i);
switch(c)
{
case (SS_UTF8_T)'\\':
tempBuf[k++] = (SS_UTF8_T)'\\';
tempBuf[k++] = (SS_UTF8_T)'\\';
escaped = 1;
break;
case (SS_UTF8_T)':':
tempBuf[k++] = (SS_UTF8_T)'\\';
tempBuf[k++] = (SS_UTF8_T)':';
escaped = 1;
break;
case (SS_UTF8_T)'=':
tempBuf[k++] = (SS_UTF8_T)'\\';
tempBuf[k++] = (SS_UTF8_T)'=';
escaped = 1;
break;
default:
@ -264,7 +272,11 @@ static void sscsshs_ChkEscapeString(SS_UTF8_T *entryBuf)
}
}
sscs_Utf8Strcpy(entryBuf, tempBuf);
if (escaped) {
free (*entryBuf);
*entryBuf = tempBuf;
return;
}
/* ############################### CODE EXITS HERE ############################# */
@ -310,7 +322,7 @@ static int32_t sscsshs_PopulateSecretBuf
retBuffer[sscs_Utf8Strlen(retBuffer)] = (SS_UTF8_T)0x0A; // add a line feed delimiter
}
sscsshs_ChkEscapeString(key);
sscsshs_ChkEscapeString(&key);
if(sscs_Utf8Strcmp(key, SSCS_CRED_SET))
{
@ -328,7 +340,7 @@ static int32_t sscsshs_PopulateSecretBuf
sscs_Utf8Strcat(retBuffer, APP_DELIMITER);
}
sscsshs_ChkEscapeString(val);
sscsshs_ChkEscapeString(&val);
if((*bufLen + (sscs_Utf8StrSize(val))) < NSSCS_MAX_SECRET_BUF_LEN)
{
sscs_Utf8Strcat(retBuffer, val);
@ -385,7 +397,7 @@ static int32_t sscsshs_PopulateBinarySecretBuf
return(NSSCS_E_PARSER_FAILURE); // create error stating non-binary buffer
}
sscsshs_ChkEscapeString(key);
sscsshs_ChkEscapeString(&key);
sscs_Utf8Strcpy((SS_UTF8_T *)retBuffer, key);
sscs_Utf8Strcat((SS_UTF8_T *)retBuffer, BINARY_DELIMITER);
len = sscs_Utf8StrSize((SS_UTF8_T *)retBuffer);
@ -1057,7 +1069,7 @@ miCASAReadSecret
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->name, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->name));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1227,7 +1239,7 @@ miCASARemoveSecret
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->name, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->name));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1373,7 +1385,7 @@ miCASAWriteSecret
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->name, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->name));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1575,13 +1587,13 @@ miCASAWriteKey
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->id, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->id));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
memcpy(escapedSHSKey, key, keyLen);
sscsshs_ChkEscapeString(escapedSHSKey);
sscsshs_ChkEscapeString(&escapedSHSKey);
memcpy(escapedSHSValue, val, valLen);
sscsshs_ChkEscapeString(escapedSHSValue);
sscsshs_ChkEscapeString(&escapedSHSValue);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1701,10 +1713,10 @@ miCASAWriteBinaryKey
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->id, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->id));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
memcpy(escapedSHSKey, key, keyLen);
sscsshs_ChkEscapeString(escapedSHSKey);
sscsshs_ChkEscapeString(&escapedSHSKey);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1821,10 +1833,10 @@ miCASAReadKey
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->id, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->id));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
memcpy(escapedSHSKey, key, keyLen);
sscsshs_ChkEscapeString(escapedSHSKey);
sscsshs_ChkEscapeString(&escapedSHSKey);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{
@ -1939,10 +1951,10 @@ miCASAReadBinaryKey
// escape delimited characters
memcpy(escapedSHSName, sharedSecretID->id, sscs_Utf8StrSize((SS_UTF8_T *)sharedSecretID->id));
sscsshs_ChkEscapeString(escapedSHSName);
sscsshs_ChkEscapeString(&escapedSHSName);
memcpy(escapedSHSKey, key, keyLen);
sscsshs_ChkEscapeString(escapedSHSKey);
sscsshs_ChkEscapeString(&escapedSHSKey);
if((escNameLen = sscs_Utf8Strlen((SS_UTF8_T *)escapedSHSName)) < 1)
{