Skip to content

Commit

Permalink
initial poshring commit
Browse files Browse the repository at this point in the history
  • Loading branch information
skyguy94 committed May 31, 2015
1 parent b0914d6 commit 349cf16
Show file tree
Hide file tree
Showing 17 changed files with 675 additions and 0 deletions.
28 changes: 28 additions & 0 deletions poshring.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "poshring", "poshring\poshring.csproj", "{4E443910-8C87-4815-8718-9E987C40098D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "poshring.tests", "poshring.tests\poshring.tests.csproj", "{ECF3AACC-075F-4706-BE75-A1B09EE6D539}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4E443910-8C87-4815-8718-9E987C40098D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4E443910-8C87-4815-8718-9E987C40098D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E443910-8C87-4815-8718-9E987C40098D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E443910-8C87-4815-8718-9E987C40098D}.Release|Any CPU.Build.0 = Release|Any CPU
{ECF3AACC-075F-4706-BE75-A1B09EE6D539}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECF3AACC-075F-4706-BE75-A1B09EE6D539}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECF3AACC-075F-4706-BE75-A1B09EE6D539}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECF3AACC-075F-4706-BE75-A1B09EE6D539}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
48 changes: 48 additions & 0 deletions poshring.tests/IntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Linq;
using NUnit.Framework;

namespace poshring.tests
{
[TestFixture]
public class IntegrationTests
{
[Test]
public void ReadsAllCredentials()
{
var cm = new CredentialsManager();
var credentials = cm.GetCredentials().ToList();

Assert.That(credentials.Count, Is.GreaterThan(0));
}

[Test]
public void ManagesPasswordCredential()
{
var cm = new CredentialsManager();

try
{
cm.AddPasswordCredential("test", "testy McTester", "dothetestydance", "test credential");
var credential = cm.GetCredentials().Single(s => s.TargetName == "test");
Assert.That(credential.UserName, Is.EqualTo("testy McTester"));
Assert.That(credential.Comment, Is.EqualTo("test credential"));
Assert.That(credential.CredentialBlob, Is.EqualTo("dothetestydance"));

credential.Comment = "Hobos ride the train.";
credential.UserName = "Biscut";
credential.CredentialBlob = "sekret";
credential.Save();

credential = cm.GetCredentials().Single(s => s.TargetName == "test");
Assert.That(credential.Comment, Is.EqualTo("Hobos ride the train."));
Assert.That(credential.UserName, Is.EqualTo("Biscut"));
Assert.That(credential.CredentialBlob, Is.EqualTo("sekret"));
}
finally
{
var credentials = cm.GetCredentials().Where(s => s.TargetName == "test").ToList();
credentials.ForEach(s => cm.DeleteCredential(s));
}
}
}
}
35 changes: 35 additions & 0 deletions poshring.tests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;

// 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("Manager.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Manager.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ecf3aacc-075f-4706-be75-a1b09ee6d539")]

// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
4 changes: 4 additions & 0 deletions poshring.tests/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NUnit" version="2.6.4" targetFramework="net45" />
</packages>
62 changes: 62 additions & 0 deletions poshring.tests/poshring.tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{ECF3AACC-075F-4706-BE75-A1B09EE6D539}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>poshring.tests</RootNamespace>
<AssemblyName>poshring.tests</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="IntegrationTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\poshring\poshring.csproj">
<Project>{4e443910-8c87-4815-8718-9e987c40098d}</Project>
<Name>poshring</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
109 changes: 109 additions & 0 deletions poshring/Credential.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace poshring
{
public class Credential : IDisposable
{
private NativeCredential _nativeCredential;
private bool _disposed;

public Credential()
: this(new NativeCredential())
{
_nativeCredential.Flags = 0;
Type = CredentialType.Generic;
_nativeCredential.AttributeCount = 0;
_nativeCredential.Persist = CredentialPersist.LocalMachine;
}

public Credential(NativeCredential nativeCredential)
{
_nativeCredential = nativeCredential;
}

public CredentialType Type
{
get { return _nativeCredential.Type; }
set { _nativeCredential.Type = value; }
}

public string TargetName
{
get { return _nativeCredential.TargetName.Substring(_nativeCredential.TargetName.IndexOf("=", StringComparison.InvariantCultureIgnoreCase)+1); }
set { _nativeCredential.TargetName = value; }
}

public string UserName
{
get { return _nativeCredential.UserName; }
set { _nativeCredential.UserName = value; }
}

public string Comment
{
get { return _nativeCredential.Comment; }
set { _nativeCredential.Comment = value; }
}

public DateTime LastWritten
{
get
{
long lastWritten = _nativeCredential.LastWritten.dwHighDateTime;
lastWritten = (lastWritten << 32) + _nativeCredential.LastWritten.dwLowDateTime;
return DateTime.FromFileTime(lastWritten);
}
}

public string CredentialBlob
{
get
{
if (_nativeCredential.CredentialBlobSize == 0) return string.Empty;
var length = (int)_nativeCredential.CredentialBlobSize / sizeof(char);
char[] chars = new char[length];
Marshal.Copy(_nativeCredential.CredentialBlob, chars, 0, length);
return new string(chars);
}
set
{
var length = value.Length*sizeof (char);
_nativeCredential.CredentialBlob = Marshal.AllocHGlobal(length);
var bytes = value.SelectMany(BitConverter.GetBytes).ToArray();
Marshal.Copy(bytes, 0, _nativeCredential.CredentialBlob, length);
_nativeCredential.CredentialBlobSize = (uint)length;
}

}

public void Save()
{
var result = UnsafeAdvapi32.CredWriteW(ref _nativeCredential, 0);
if (!result)
{
var error = (CredentialErrors) Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not save credential.");
}
}

public void Dispose()
{
Dispose(true);
}

~Credential()
{
Dispose(false);
}

protected void Dispose(bool disposing)
{
if (_disposed) return;

_disposed = true;
UnsafeAdvapi32.CredFree(_nativeCredential);
}
}
}
15 changes: 15 additions & 0 deletions poshring/CredentialManagerException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace poshring
{
class CredentialManagerException : Exception
{
public CredentialErrors Error;

public CredentialManagerException(CredentialErrors error, string message)
: base(message)
{
Error = error;
}
}
}
49 changes: 49 additions & 0 deletions poshring/CredentialsManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;

namespace poshring
{
public class CredentialsManager
{
public IEnumerable<Credential> GetCredentials()
{
int count;
IntPtr ptr;
if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

var credentials = Enumerable.Range(0, count)
.Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
.Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
return credentials;
}

public void AddPasswordCredential(string targetName, string userName, string password, string comment)
{
using (var credential = new Credential
{
TargetName = targetName,
UserName = userName,
CredentialBlob = password,
Comment = comment
})
{
credential.Save();
}
}

public void DeleteCredential(Credential credential)
{
if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
{
var error = (CredentialErrors)Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not delete credential.");
}
}
}
}
36 changes: 36 additions & 0 deletions poshring/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// 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("poshring")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("poshring")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d18cf2e-8d7d-4675-a78c-3cbc93ff1081")]

// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading

0 comments on commit 349cf16

Please sign in to comment.