Merge pull request #2567 from MediaBrowser/beta

Beta
This commit is contained in:
Luke 2017-04-07 15:26:59 -04:00 committed by GitHub
commit 7c55cd08cb
299 changed files with 39222 additions and 516 deletions

View File

@ -137,19 +137,19 @@ namespace BDInfo
}
if (DirectoryBDJO != null &&
_fileSystem.GetFiles(DirectoryBDJO.FullName).Any())
_fileSystem.GetFilePaths(DirectoryBDJO.FullName).Any())
{
IsBDJava = true;
}
if (DirectorySNP != null &&
GetFiles(DirectorySNP.FullName, ".mnv").Any())
GetFilePaths(DirectorySNP.FullName, ".mnv").Any())
{
IsPSP = true;
}
if (DirectorySSIF != null &&
_fileSystem.GetFiles(DirectorySSIF.FullName).Any())
_fileSystem.GetFilePaths(DirectorySSIF.FullName).Any())
{
Is3D = true;
}
@ -206,7 +206,12 @@ namespace BDInfo
private IEnumerable<FileSystemMetadata> GetFiles(string path, string extension)
{
return _fileSystem.GetFiles(path).Where(i => string.Equals(i.Extension, extension, StringComparison.OrdinalIgnoreCase));
return _fileSystem.GetFiles(path, new[] { extension }, false, false);
}
private IEnumerable<string> GetFilePaths(string path, string extension)
{
return _fileSystem.GetFilePaths(path, new[] { extension }, false, false);
}
public void Scan()

View File

@ -23,6 +23,8 @@ namespace Emby.Common.Implementations.IO
private string _tempPath;
private SharpCifsFileSystem _sharpCifsFileSystem;
public ManagedFileSystem(ILogger logger, IEnvironmentInfo environmentInfo, string tempPath)
{
Logger = logger;
@ -34,6 +36,8 @@ namespace Emby.Common.Implementations.IO
environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.OSX;
SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
_sharpCifsFileSystem = new SharpCifsFileSystem(environmentInfo.OperatingSystem);
}
public void AddShortcutHandler(IShortcutHandler handler)
@ -65,14 +69,6 @@ namespace Emby.Common.Implementations.IO
}
}
public char PathSeparator
{
get
{
return Path.PathSeparator;
}
}
public string GetFullPath(string path)
{
return Path.GetFullPath(path);
@ -168,6 +164,11 @@ namespace Emby.Common.Implementations.IO
throw new ArgumentNullException("path");
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemInfo(path);
}
// Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
if (Path.HasExtension(path))
{
@ -208,6 +209,11 @@ namespace Emby.Common.Implementations.IO
throw new ArgumentNullException("path");
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileInfo(path);
}
var fileInfo = new FileInfo(path);
return GetFileSystemMetadata(fileInfo);
@ -228,6 +234,11 @@ namespace Emby.Common.Implementations.IO
throw new ArgumentNullException("path");
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectoryInfo(path);
}
var fileInfo = new DirectoryInfo(path);
return GetFileSystemMetadata(fileInfo);
@ -374,6 +385,11 @@ namespace Emby.Common.Implementations.IO
/// <returns>FileStream.</returns>
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
}
if (_supportsAsyncFileStreams && isAsync)
{
return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 262144, true);
@ -386,8 +402,8 @@ namespace Emby.Common.Implementations.IO
{
switch (mode)
{
case FileOpenMode.Append:
return FileMode.Append;
//case FileOpenMode.Append:
// return FileMode.Append;
case FileOpenMode.Create:
return FileMode.Create;
case FileOpenMode.CreateNew:
@ -396,8 +412,8 @@ namespace Emby.Common.Implementations.IO
return FileMode.Open;
case FileOpenMode.OpenOrCreate:
return FileMode.OpenOrCreate;
case FileOpenMode.Truncate:
return FileMode.Truncate;
//case FileOpenMode.Truncate:
// return FileMode.Truncate;
default:
throw new Exception("Unrecognized FileOpenMode");
}
@ -407,8 +423,8 @@ namespace Emby.Common.Implementations.IO
{
switch (mode)
{
case FileAccessMode.ReadWrite:
return FileAccess.ReadWrite;
//case FileAccessMode.ReadWrite:
// return FileAccess.ReadWrite;
case FileAccessMode.Write:
return FileAccess.Write;
case FileAccessMode.Read:
@ -437,6 +453,12 @@ namespace Emby.Common.Implementations.IO
public void SetHidden(string path, bool isHidden)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.SetHidden(path, isHidden);
return;
}
var info = GetFileInfo(path);
if (info.Exists && info.IsHidden != isHidden)
@ -456,6 +478,12 @@ namespace Emby.Common.Implementations.IO
public void SetReadOnly(string path, bool isReadOnly)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.SetReadOnly(path, isReadOnly);
return;
}
var info = GetFileInfo(path);
if (info.Exists && info.IsReadOnly != isReadOnly)
@ -508,6 +536,16 @@ namespace Emby.Common.Implementations.IO
CopyFile(temp1, file2, true);
}
private char GetDirectorySeparatorChar(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
}
return Path.DirectorySeparatorChar;
}
public bool AreEqual(string path1, string path2)
{
if (path1 == null && path2 == null)
@ -520,8 +558,8 @@ namespace Emby.Common.Implementations.IO
return false;
}
path1 = path1.TrimEnd(DirectorySeparatorChar);
path2 = path2.TrimEnd(DirectorySeparatorChar);
path1 = path1.TrimEnd(GetDirectorySeparatorChar(path1));
path2 = path2.TrimEnd(GetDirectorySeparatorChar(path2));
return string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase);
}
@ -538,7 +576,9 @@ namespace Emby.Common.Implementations.IO
throw new ArgumentNullException("path");
}
return path.IndexOf(parentPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
var separatorChar = GetDirectorySeparatorChar(parentPath);
return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
}
public bool IsRootPath(string path)
@ -570,7 +610,7 @@ namespace Emby.Common.Implementations.IO
return path;
}
return path.TrimEnd(Path.DirectorySeparatorChar);
return path.TrimEnd(GetDirectorySeparatorChar(path));
}
public string GetFileNameWithoutExtension(FileSystemMetadata info)
@ -609,6 +649,12 @@ namespace Emby.Common.Implementations.IO
public void DeleteFile(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.DeleteFile(path);
return;
}
var fileInfo = GetFileInfo(path);
if (fileInfo.Exists)
@ -628,11 +674,23 @@ namespace Emby.Common.Implementations.IO
public void DeleteDirectory(string path, bool recursive)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.DeleteDirectory(path, recursive);
return;
}
Directory.Delete(path, recursive);
}
public void CreateDirectory(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.CreateDirectory(path);
return;
}
Directory.CreateDirectory(path);
}
@ -655,121 +713,273 @@ namespace Emby.Common.Implementations.IO
public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectories(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return ToMetadata(path, new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
}
public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
{
return GetFiles(path, null, false, recursive);
}
public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return ToMetadata(path, new DirectoryInfo(path).EnumerateFiles("*", searchOption));
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
{
return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
}
var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
if (extensions != null && extensions.Length > 0)
{
files = files.Where(i =>
{
var ext = i.Extension;
if (ext == null)
{
return false;
}
return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
});
}
return ToMetadata(files);
}
public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
}
var directoryInfo = new DirectoryInfo(path);
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
if (EnableFileSystemRequestConcat)
{
return ToMetadata(path, directoryInfo.EnumerateDirectories("*", searchOption))
.Concat(ToMetadata(path, directoryInfo.EnumerateFiles("*", searchOption)));
return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
.Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
}
return ToMetadata(path, directoryInfo.EnumerateFileSystemInfos("*", searchOption));
return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", searchOption));
}
private IEnumerable<FileSystemMetadata> ToMetadata(string parentPath, IEnumerable<FileSystemInfo> infos)
private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
{
return infos.Select(GetFileSystemMetadata);
}
public string[] ReadAllLines(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllLines(path);
}
return File.ReadAllLines(path);
}
public void WriteAllLines(string path, IEnumerable<string> lines)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllLines(path, lines);
return;
}
File.WriteAllLines(path, lines);
}
public Stream OpenRead(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.OpenRead(path);
}
return File.OpenRead(path);
}
public void CopyFile(string source, string target, bool overwrite)
{
if (_sharpCifsFileSystem.IsEnabledForPath(source))
{
_sharpCifsFileSystem.CopyFile(source, target, overwrite);
return;
}
File.Copy(source, target, overwrite);
}
public void MoveFile(string source, string target)
{
if (_sharpCifsFileSystem.IsEnabledForPath(source))
{
_sharpCifsFileSystem.MoveFile(source, target);
return;
}
File.Move(source, target);
}
public void MoveDirectory(string source, string target)
{
if (_sharpCifsFileSystem.IsEnabledForPath(source))
{
_sharpCifsFileSystem.MoveDirectory(source, target);
return;
}
Directory.Move(source, target);
}
public bool DirectoryExists(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.DirectoryExists(path);
}
return Directory.Exists(path);
}
public bool FileExists(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.FileExists(path);
}
return File.Exists(path);
}
public string ReadAllText(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllText(path);
}
return File.ReadAllText(path);
}
public byte[] ReadAllBytes(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllBytes(path);
}
return File.ReadAllBytes(path);
}
public void WriteAllText(string path, string text, Encoding encoding)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllText(path, text, encoding);
return;
}
File.WriteAllText(path, text, encoding);
}
public void WriteAllText(string path, string text)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllText(path, text);
return;
}
File.WriteAllText(path, text);
}
public void WriteAllBytes(string path, byte[] bytes)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllBytes(path, bytes);
return;
}
File.WriteAllBytes(path, bytes);
}
public string ReadAllText(string path, Encoding encoding)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllText(path, encoding);
}
return File.ReadAllText(path, encoding);
}
public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateDirectories(path, "*", searchOption);
}
public IEnumerable<string> GetFilePaths(string path, bool recursive = false)
{
return GetFilePaths(path, null, false, recursive);
}
public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateFiles(path, "*", searchOption);
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
{
return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
}
var files = Directory.EnumerateFiles(path, "*", searchOption);
if (extensions != null && extensions.Length > 0)
{
files = files.Where(i =>
{
var ext = Path.GetExtension(i);
if (ext == null)
{
return false;
}
return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
});
}
return files;
}
public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
}

View File

@ -0,0 +1,409 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using System.Net;
using System.Security;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs
{
/// <summary>
/// This class uses a static
/// <see cref="Properties">Sharpen.Properties</see>
/// to act
/// as a cental repository for all jCIFS configuration properties. It cannot be
/// instantiated. Similar to <code>System</code> properties the namespace
/// is global therefore property names should be unique. Before use,
/// the <code>load</code> method should be called with the name of a
/// <code>Properties</code> file (or <code>null</code> indicating no
/// file) to initialize the <code>Config</code>. The <code>System</code>
/// properties will then populate the <code>Config</code> as well potentially
/// overwriting properties from the file. Thus properties provided on the
/// commandline with the <code>-Dproperty.name=value</code> VM parameter
/// will override properties from the configuration file.
///
/// There are several ways to set jCIFS properties. See
/// the <a href="../overview-summary.html#scp">overview page of the API
/// documentation</a> for details.
/// </summary>
public class Config
{
/// <summary>The static <code>Properties</code>.</summary>
/// <remarks>The static <code>Properties</code>.</remarks>
private static Properties _prp = new Properties();
private static LogStream _log;
public static string DefaultOemEncoding = "UTF-8"; //"Cp850";
static Config()
{
int level;
FileInputStream fis = null;
_log = LogStream.GetInstance();
try
{
string filename = Runtime.GetProperty("jcifs.properties");
if (filename != null && filename.Length > 1)
{
fis = new FileInputStream(filename);
}
Load(fis);
if (fis != null)
{
fis.Close();
}
}
catch (IOException ioe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ioe, _log);
}
}
if ((level = GetInt("jcifs.util.loglevel", -1)) != -1)
{
_log.SetLevel(level);
}
try
{
Runtime.GetBytesForString(string.Empty, DefaultOemEncoding);
}
catch (Exception ex)
{
if (_log.Level >= 2)
{
_log.WriteLine("WARNING: The default OEM encoding " + DefaultOemEncoding + " does not appear to be supported by this JRE. The default encoding will be US-ASCII."
);
}
//DEFAULT_OEM_ENCODING = "US-ASCII";
}
if (_log.Level >= 4)
{
try
{
_prp.Store(_log);
}
catch (IOException)
{
}
}
}
/// <summary>
/// This static method registers the SMB URL protocol handler which is
/// required to use SMB URLs with the <tt>java.net.URL</tt> class.
/// </summary>
/// <remarks>
/// This static method registers the SMB URL protocol handler which is
/// required to use SMB URLs with the <tt>java.net.URL</tt> class. If this
/// method is not called before attempting to create an SMB URL with the
/// URL class the following exception will occur:
/// <blockquote><pre>
/// Exception MalformedURLException: unknown protocol: smb
/// at java.net.URL.<init>(URL.java:480)
/// at java.net.URL.<init>(URL.java:376)
/// at java.net.URL.<init>(URL.java:330)
/// at jcifs.smb.SmbFile.<init>(SmbFile.java:355)
/// ...
/// </pre><blockquote>
/// </remarks>
public static void RegisterSmbURLHandler()
{
throw new NotImplementedException();
}
// supress javadoc constructor summary by removing 'protected'
/// <summary>Set the default properties of the static Properties used by <tt>Config</tt>.
/// </summary>
/// <remarks>
/// Set the default properties of the static Properties used by <tt>Config</tt>. This permits
/// a different Properties object/file to be used as the source of properties for
/// use by the jCIFS library. The Properties must be set <i>before jCIFS
/// classes are accessed</i> as most jCIFS classes load properties statically once.
/// Using this method will also override properties loaded
/// using the <tt>-Djcifs.properties=</tt> commandline parameter.
/// </remarks>
public static void SetProperties(Properties prp)
{
Config._prp = new Properties(prp);
try
{
Config._prp.PutAll(Runtime.GetProperties());
}
catch (SecurityException)
{
if (_log.Level > 1)
{
_log.WriteLine("SecurityException: jcifs will ignore System properties");
}
}
}
/// <summary>
/// Load the <code>Config</code> with properties from the stream
/// <code>in</code> from a <code>Properties</code> file.
/// </summary>
/// <remarks>
/// Load the <code>Config</code> with properties from the stream
/// <code>in</code> from a <code>Properties</code> file.
/// </remarks>
/// <exception cref="System.IO.IOException"></exception>
public static void Load(InputStream input)
{
if (input != null)
{
_prp.Load(input);
}
try
{
_prp.PutAll(Runtime.GetProperties());
}
catch (SecurityException)
{
if (_log.Level > 1)
{
_log.WriteLine("SecurityException: jcifs will ignore System properties");
}
}
}
/// <exception cref="System.IO.IOException"></exception>
public static void Store(OutputStream output, string header)
{
_prp.Store(output);
}
/// <summary>Add a property.</summary>
/// <remarks>Add a property.</remarks>
public static void SetProperty(string key, string value)
{
_prp.SetProperty(key, value);
}
/// <summary>Retrieve a property as an <code>Object</code>.</summary>
/// <remarks>Retrieve a property as an <code>Object</code>.</remarks>
public static object Get(string key)
{
return _prp.GetProperty(key);
}
/// <summary>Retrieve a <code>String</code>.</summary>
/// <remarks>
/// Retrieve a <code>String</code>. If the key cannot be found,
/// the provided <code>def</code> default parameter will be returned.
/// </remarks>
public static string GetProperty(string key, string def)
{
return (string)_prp.GetProperty(key, def);
}
/// <summary>Retrieve a <code>String</code>.</summary>
/// <remarks>Retrieve a <code>String</code>. If the property is not found, <code>null</code> is returned.
/// </remarks>
public static string GetProperty(string key)
{
return (string)_prp.GetProperty(key);
}
/// <summary>Retrieve an <code>int</code>.</summary>
/// <remarks>
/// Retrieve an <code>int</code>. If the key does not exist or
/// cannot be converted to an <code>int</code>, the provided default
/// argument will be returned.
/// </remarks>
public static int GetInt(string key, int def)
{
string s = (string)_prp.GetProperty(key);
if (s != null)
{
try
{
def = Convert.ToInt32(s);
}
catch (FormatException nfe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(nfe, _log);
}
}
}
return def;
}
/// <summary>Retrieve an <code>int</code>.</summary>
/// <remarks>Retrieve an <code>int</code>. If the property is not found, <code>-1</code> is returned.
/// </remarks>
public static int GetInt(string key)
{
string s = (string)_prp.GetProperty(key);
int result = -1;
if (s != null)
{
try
{
result = Convert.ToInt32(s);
}
catch (FormatException nfe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(nfe, _log);
}
}
}
return result;
}
/// <summary>Retrieve a <code>long</code>.</summary>
/// <remarks>
/// Retrieve a <code>long</code>. If the key does not exist or
/// cannot be converted to a <code>long</code>, the provided default
/// argument will be returned.
/// </remarks>
public static long GetLong(string key, long def)
{
string s = (string)_prp.GetProperty(key);
if (s != null)
{
try
{
def = long.Parse(s);
}
catch (FormatException nfe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(nfe, _log);
}
}
}
return def;
}
/// <summary>Retrieve an <code>InetAddress</code>.</summary>
/// <remarks>
/// Retrieve an <code>InetAddress</code>. If the address is not
/// an IP address and cannot be resolved <code>null</code> will
/// be returned.
/// </remarks>
public static IPAddress GetInetAddress(string key, IPAddress def)
{
string addr = (string)_prp.GetProperty(key);
if (addr != null)
{
try
{
def = Extensions.GetAddressByName(addr);
}
catch (UnknownHostException uhe)
{
if (_log.Level > 0)
{
_log.WriteLine(addr);
Runtime.PrintStackTrace(uhe, _log);
}
}
}
return def;
}
public static IPAddress GetLocalHost()
{
string addr = (string)_prp.GetProperty("jcifs.smb.client.laddr");
if (addr != null)
{
try
{
return Extensions.GetAddressByName(addr);
}
catch (UnknownHostException uhe)
{
if (_log.Level > 0)
{
_log.WriteLine("Ignoring jcifs.smb.client.laddr address: " + addr);
Runtime.PrintStackTrace(uhe, _log);
}
}
}
return null;
}
/// <summary>Retrieve a boolean value.</summary>
/// <remarks>Retrieve a boolean value. If the property is not found, the value of <code>def</code> is returned.
/// </remarks>
public static bool GetBoolean(string key, bool def)
{
string b = GetProperty(key);
if (b != null)
{
def = b.ToLower().Equals("true");
}
return def;
}
/// <summary>
/// Retrieve an array of <tt>InetAddress</tt> created from a property
/// value containting a <tt>delim</tt> separated list of hostnames and/or
/// ipaddresses.
/// </summary>
/// <remarks>
/// Retrieve an array of <tt>InetAddress</tt> created from a property
/// value containting a <tt>delim</tt> separated list of hostnames and/or
/// ipaddresses.
/// </remarks>
public static IPAddress[] GetInetAddressArray(string key, string delim, IPAddress
[] def)
{
string p = GetProperty(key);
if (p != null)
{
StringTokenizer tok = new StringTokenizer(p, delim);
int len = tok.CountTokens();
IPAddress[] arr = new IPAddress[len];
for (int i = 0; i < len; i++)
{
string addr = tok.NextToken();
try
{
arr[i] = Extensions.GetAddressByName(addr);
}
catch (UnknownHostException uhe)
{
if (_log.Level > 0)
{
_log.WriteLine(addr);
Runtime.PrintStackTrace(uhe, _log);
}
return def;
}
}
return arr;
}
return def;
}
}
}

View File

@ -0,0 +1,102 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
using SharpCifs.Util;
namespace SharpCifs.Dcerpc
{
public class DcerpcBind : DcerpcMessage
{
internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED"
, "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
};
internal static string GetResultMessage(int result)
{
return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4
);
}
public override DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(GetResultMessage(Result));
}
return null;
}
internal DcerpcBinding Binding;
internal int MaxXmit;
internal int MaxRecv;
public DcerpcBind()
{
}
internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle)
{
this.Binding = binding;
MaxXmit = handle.MaxXmit;
MaxRecv = handle.MaxRecv;
Ptype = 11;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
public override int GetOpnum()
{
return 0;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_short(MaxXmit);
dst.Enc_ndr_short(MaxRecv);
dst.Enc_ndr_long(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
Binding.Uuid.Encode(dst);
dst.Enc_ndr_short(Binding.Major);
dst.Enc_ndr_short(Binding.Minor);
DcerpcConstants.DcerpcUuidSyntaxNdr.Encode(dst);
dst.Enc_ndr_long(2);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
src.Dec_ndr_short();
src.Dec_ndr_short();
src.Dec_ndr_long();
int n = src.Dec_ndr_short();
src.Advance(n);
src.Align(4);
src.Dec_ndr_small();
src.Align(4);
Result = src.Dec_ndr_short();
src.Dec_ndr_short();
src.Advance(20);
}
}
}

View File

@ -0,0 +1,122 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Dcerpc.Msrpc;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcBinding
{
private static Hashtable _interfaces;
static DcerpcBinding()
{
_interfaces = new Hashtable();
_interfaces.Put("srvsvc", Srvsvc.GetSyntax());
_interfaces.Put("lsarpc", Lsarpc.GetSyntax());
_interfaces.Put("samr", Samr.GetSyntax());
_interfaces.Put("netdfs", Netdfs.GetSyntax());
}
public static void AddInterface(string name, string syntax)
{
_interfaces.Put(name, syntax);
}
internal string Proto;
internal string Server;
internal string Endpoint;
internal Hashtable Options;
internal Uuid Uuid;
internal int Major;
internal int Minor;
internal DcerpcBinding(string proto, string server)
{
this.Proto = proto;
this.Server = server;
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
internal virtual void SetOption(string key, object val)
{
if (key.Equals("endpoint"))
{
Endpoint = val.ToString().ToLower();
if (Endpoint.StartsWith("\\pipe\\"))
{
string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
if (iface != null)
{
int c;
int p;
c = iface.IndexOf(':');
p = iface.IndexOf('.', c + 1);
Uuid = new Uuid(Runtime.Substring(iface, 0, c));
Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
return;
}
}
throw new DcerpcException("Bad endpoint: " + Endpoint);
}
if (Options == null)
{
Options = new Hashtable();
}
Options.Put(key, val);
}
internal virtual object GetOption(string key)
{
if (key.Equals("endpoint"))
{
return Endpoint;
}
if (Options != null)
{
return Options.Get(key);
}
return null;
}
public override string ToString()
{
/* string ret = proto + ":" + server + "[" + endpoint;
if (options != null)
{
Iterator iter = (Iterator) options.Keys.GetEnumerator();
while (iter.HasNext())
{
object key = iter.Next();
object val = options.Get(key);
ret += "," + key + "=" + val;
}
}
ret += "]";
return ret; */
return null;
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public static class DcerpcConstants
{
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"
);
public static int DcerpcFirstFrag = unchecked(0x01);
public static int DcerpcLastFrag = unchecked(0x02);
public static int DcerpcPendingCancel = unchecked(0x04);
public static int DcerpcReserved1 = unchecked(0x08);
public static int DcerpcConcMpx = unchecked(0x10);
public static int DcerpcDidNotExecute = unchecked(0x20);
public static int DcerpcMaybe = unchecked(0x40);
public static int DcerpcObjectUuid = unchecked(0x80);
}
}

View File

@ -0,0 +1,48 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public static class DcerpcError
{
public static int DcerpcFaultOther = unchecked(0x00000001);
public static int DcerpcFaultAccessDenied = unchecked(0x00000005);
public static int DcerpcFaultCantPerform = unchecked(0x000006D8);
public static int DcerpcFaultNdr = unchecked(0x000006F7);
public static int DcerpcFaultInvalidTag = unchecked(0x1C000006);
public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A);
public static int DcerpcFaultOpRngError = unchecked(0x1C010002);
public static int DcerpcFaultUnkIf = unchecked(0x1C010003);
public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied
, DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch
, DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError };
public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER"
, "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR",
"DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR"
, "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" };
}
}

View File

@ -0,0 +1,93 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcException : IOException
{
internal static string GetMessageByDcerpcError(int errcode)
{
int min = 0;
int max = DcerpcError.DcerpcFaultCodes.Length;
while (max >= min)
{
int mid = (min + max) / 2;
if (errcode > DcerpcError.DcerpcFaultCodes[mid])
{
min = mid + 1;
}
else
{
if (errcode < DcerpcError.DcerpcFaultCodes[mid])
{
max = mid - 1;
}
else
{
return DcerpcError.DcerpcFaultMessages[mid];
}
}
}
return "0x" + Hexdump.ToHexString(errcode, 8);
}
private int _error;
private Exception _rootCause;
internal DcerpcException(int error) : base(GetMessageByDcerpcError(error))
{
this._error = error;
}
public DcerpcException(string msg) : base(msg)
{
}
public DcerpcException(string msg, Exception rootCause) : base(msg)
{
this._rootCause = rootCause;
}
public virtual int GetErrorCode()
{
return _error;
}
public virtual Exception GetRootCause()
{
return _rootCause;
}
public override string ToString()
{
if (_rootCause != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Runtime.PrintStackTrace(_rootCause, pw);
return base.ToString() + "\n" + sw;
}
return base.ToString();
}
}
}

View File

@ -0,0 +1,332 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Dcerpc.Ndr;
using SharpCifs.Smb;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public abstract class DcerpcHandle
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
protected internal static DcerpcBinding ParseBinding(string str)
{
int state;
int mark;
int si;
char[] arr = str.ToCharArray();
string proto = null;
string key = null;
DcerpcBinding binding = null;
state = mark = si = 0;
do
{
char ch = arr[si];
switch (state)
{
case 0:
{
if (ch == ':')
{
proto = Runtime.Substring(str, mark, si);
mark = si + 1;
state = 1;
}
break;
}
case 1:
{
if (ch == '\\')
{
mark = si + 1;
break;
}
state = 2;
goto case 2;
}
case 2:
{
if (ch == '[')
{
string server = Runtime.Substring(str, mark, si).Trim();
if (server.Length == 0)
{
server = "127.0.0.1";
}
binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si));
mark = si + 1;
state = 5;
}
break;
}
case 5:
{
if (ch == '=')
{
key = Runtime.Substring(str, mark, si).Trim();
mark = si + 1;
}
else
{
if (ch == ',' || ch == ']')
{
string val = Runtime.Substring(str, mark, si).Trim();
if (key == null)
{
key = "endpoint";
}
binding.SetOption(key, val);
key = null;
}
}
break;
}
default:
{
si = arr.Length;
break;
}
}
si++;
}
while (si < arr.Length);
if (binding == null || binding.Endpoint == null)
{
throw new DcerpcException("Invalid binding URL: " + str);
}
return binding;
}
protected internal DcerpcBinding Binding;
protected internal int MaxXmit = 4280;
protected internal int MaxRecv;
protected internal int State;
protected internal IDcerpcSecurityProvider SecurityProvider;
private static int _callId = 1;
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth)
{
if (url.StartsWith("ncacn_np:"))
{
return new DcerpcPipeHandle(url, auth);
}
throw new DcerpcException("DCERPC transport not supported: " + url);
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Bind()
{
lock (this)
{
try
{
State = 1;
DcerpcMessage bind = new DcerpcBind(Binding, this);
Sendrecv(bind);
}
catch (IOException ioe)
{
State = 0;
throw;
}
}
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Sendrecv(DcerpcMessage msg)
{
byte[] stub;
byte[] frag;
NdrBuffer buf;
NdrBuffer fbuf;
bool isLast;
bool isDirect;
DcerpcException de;
if (State == 0)
{
Bind();
}
isDirect = true;
stub = BufferCache.GetBuffer();
try
{
int off;
int tot;
int n;
buf = new NdrBuffer(stub, 0);
msg.Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
msg.CallId = _callId++;
msg.Encode(buf);
if (SecurityProvider != null)
{
buf.SetIndex(0);
SecurityProvider.Wrap(buf);
}
tot = buf.GetLength() - 24;
off = 0;
while (off < tot)
{
n = tot - off;
if ((24 + n) > MaxXmit)
{
msg.Flags &= ~DcerpcConstants.DcerpcLastFrag;
n = MaxXmit - 24;
}
else
{
msg.Flags |= DcerpcConstants.DcerpcLastFrag;
isDirect = false;
msg.AllocHint = n;
}
msg.Length = 24 + n;
if (off > 0)
{
msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
}
if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag |
DcerpcConstants.DcerpcLastFrag))
{
buf.Start = off;
buf.Reset();
msg.Encode_header(buf);
buf.Enc_ndr_long(msg.AllocHint);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(msg.GetOpnum());
}
DoSendFragment(stub, off, msg.Length, isDirect);
off += n;
}
DoReceiveFragment(stub, isDirect);
buf.Reset();
buf.SetIndex(8);
buf.SetLength(buf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(buf);
}
buf.SetIndex(0);
msg.Decode_header(buf);
off = 24;
if (msg.Ptype == 2 && msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
{
off = msg.Length;
}
frag = null;
fbuf = null;
while (msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
{
int stubFragLen;
if (frag == null)
{
frag = new byte[MaxRecv];
fbuf = new NdrBuffer(frag, 0);
}
DoReceiveFragment(frag, isDirect);
fbuf.Reset();
fbuf.SetIndex(8);
fbuf.SetLength(fbuf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(fbuf);
}
fbuf.Reset();
msg.Decode_header(fbuf);
stubFragLen = msg.Length - 24;
if ((off + stubFragLen) > stub.Length)
{
// shouldn't happen if alloc_hint is correct or greater
byte[] tmp = new byte[off + stubFragLen];
Array.Copy(stub, 0, tmp, 0, off);
stub = tmp;
}
Array.Copy(frag, 24, stub, off, stubFragLen);
off += stubFragLen;
}
buf = new NdrBuffer(stub, 0);
msg.Decode(buf);
}
finally
{
BufferCache.ReleaseBuffer(stub);
}
if ((de = msg.GetResult()) != null)
{
throw de;
}
}
public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider
)
{
this.SecurityProvider = securityProvider;
}
public virtual string GetServer()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetServer();
}
return null;
}
public virtual Principal GetPrincipal()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetPrincipal();
}
return null;
}
public override string ToString()
{
return Binding.ToString();
}
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoSendFragment(byte[] buf, int off, int length,
bool isDirect);
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect);
/// <exception cref="System.IO.IOException"></exception>
public abstract void Close();
public DcerpcHandle()
{
MaxRecv = MaxXmit;
}
}
}

View File

@ -0,0 +1,150 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public abstract class DcerpcMessage : NdrObject
{
protected internal int Ptype = -1;
protected internal int Flags;
protected internal int Length;
protected internal int CallId;
protected internal int AllocHint;
protected internal int Result;
public virtual bool IsFlagSet(int flag)
{
return (Flags & flag) == flag;
}
public virtual void UnsetFlag(int flag)
{
Flags &= ~flag;
}
public virtual void SetFlag(int flag)
{
Flags |= flag;
}
public virtual DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(Result);
}
return null;
}
internal virtual void Encode_header(NdrBuffer buf)
{
buf.Enc_ndr_small(5);
buf.Enc_ndr_small(0);
buf.Enc_ndr_small(Ptype);
buf.Enc_ndr_small(Flags);
buf.Enc_ndr_long(unchecked(0x00000010));
buf.Enc_ndr_short(Length);
buf.Enc_ndr_short(0);
buf.Enc_ndr_long(CallId);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
internal virtual void Decode_header(NdrBuffer buf)
{
if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0)
{
throw new NdrException("DCERPC version not supported");
}
Ptype = buf.Dec_ndr_small();
Flags = buf.Dec_ndr_small();
if (buf.Dec_ndr_long() != unchecked(0x00000010))
{
throw new NdrException("Data representation not supported");
}
Length = buf.Dec_ndr_short();
if (buf.Dec_ndr_short() != 0)
{
throw new NdrException("DCERPC authentication not supported");
}
CallId = buf.Dec_ndr_long();
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer buf)
{
int start = buf.GetIndex();
int allocHintIndex = 0;
buf.Advance(16);
if (Ptype == 0)
{
allocHintIndex = buf.GetIndex();
buf.Enc_ndr_long(0);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(GetOpnum());
}
Encode_in(buf);
Length = buf.GetIndex() - start;
if (Ptype == 0)
{
buf.SetIndex(allocHintIndex);
AllocHint = Length - allocHintIndex;
buf.Enc_ndr_long(AllocHint);
}
buf.SetIndex(start);
Encode_header(buf);
buf.SetIndex(start + Length);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer buf)
{
Decode_header(buf);
if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13)
{
throw new NdrException("Unexpected ptype: " + Ptype);
}
if (Ptype == 2 || Ptype == 3)
{
AllocHint = buf.Dec_ndr_long();
buf.Dec_ndr_short();
buf.Dec_ndr_short();
}
if (Ptype == 3 || Ptype == 13)
{
Result = buf.Dec_ndr_long();
}
else
{
Decode_out(buf);
}
}
public abstract int GetOpnum();
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode_in(NdrBuffer dst);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode_out(NdrBuffer src);
}
}

View File

@ -0,0 +1,135 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Smb;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcPipeHandle : DcerpcHandle
{
internal SmbNamedPipe Pipe;
internal SmbFileInputStream In;
internal SmbFileOutputStream Out;
internal bool IsStart = true;
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
{
Binding = ParseBinding(url);
url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint
, 6);
string @params = string.Empty;
string server;
string address;
server = (string)Binding.GetOption("server");
if (server != null)
{
@params += "&server=" + server;
}
address = (string)Binding.GetOption("address");
if (server != null)
{
@params += "&address=" + address;
}
if (@params.Length > 0)
{
url += "?" + Runtime.Substring(@params, 1);
}
Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr
| SmbNamedPipe.PipeTypeDceTransact, auth);
}
/// <exception cref="System.IO.IOException"></exception>
protected internal override void DoSendFragment(byte[] buf, int off, int length,
bool isDirect)
{
if (Out != null && Out.IsOpen() == false)
{
throw new IOException("DCERPC pipe is no longer open");
}
if (In == null)
{
In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream();
}
if (Out == null)
{
Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream();
}
if (isDirect)
{
Out.WriteDirect(buf, off, length, 1);
return;
}
Out.Write(buf, off, length);
}
/// <exception cref="System.IO.IOException"></exception>
protected internal override void DoReceiveFragment(byte[] buf, bool isDirect)
{
int off;
int flags;
int length;
if (buf.Length < MaxRecv)
{
throw new ArgumentException("buffer too small");
}
if (IsStart && !isDirect)
{
// start of new frag, do trans
off = In.Read(buf, 0, 1024);
}
else
{
off = In.ReadDirect(buf, 0, buf.Length);
}
if (buf[0] != 5 && buf[1] != 0)
{
throw new IOException("Unexpected DCERPC PDU header");
}
flags = buf[3] & unchecked(0xFF);
// next read is start of new frag
IsStart = (flags & DcerpcConstants.DcerpcLastFrag) == DcerpcConstants.DcerpcLastFrag;
length = Encdec.Dec_uint16le(buf, 8);
if (length > MaxRecv)
{
throw new IOException("Unexpected fragment length: " + length);
}
while (off < length)
{
off += In.ReadDirect(buf, off, length - off);
}
}
/// <exception cref="System.IO.IOException"></exception>
public override void Close()
{
State = 0;
if (Out != null)
{
Out.Close();
}
}
}
}

View File

@ -0,0 +1,29 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public interface IDcerpcSecurityProvider
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Wrap(NdrBuffer outgoing);
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Unwrap(NdrBuffer incoming);
}
}

View File

@ -0,0 +1,43 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class LsaPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public LsaPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -0,0 +1,34 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
internal class LsarSidArrayX : Lsarpc.LsarSidArray
{
internal LsarSidArrayX(Sid[] sids)
{
NumSids = sids.Length;
this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
for (int si = 0; si < sids.Length; si++)
{
this.Sids[si] = new Lsarpc.LsarSidPtr();
this.Sids[si].Sid = sids[si];
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
{
public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
{
Info.Level = Level;
Info.E = new Netdfs.DfsEnumArray200();
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
public virtual IFileEntry[] GetEntries()
{
Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
for (int i = 0; i < a200.Count; i++)
{
entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
}
return entries;
}
}
}

View File

@ -0,0 +1,29 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain
{
public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags
, Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0)
{
this.Sam = sam;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,29 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias
{
public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids
) : base(aliasHandle, sids)
{
this.Sids = sids;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,34 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcLookupSids : Lsarpc.LsarLookupSids
{
internal Sid[] sids;
public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle
, new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray
(), 1, sids.Length)
{
this.sids = sids;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,35 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
{
public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle
) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle)
{
ObjectAttributes.Length = 24;
Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();
qos.Length = 12;
qos.ImpersonationLevel = 2;
qos.ContextMode = 1;
qos.EffectiveOnly = 0;
ObjectAttributes.SecurityQualityOfService = qos;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,30 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy
{
public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject
info) : base(policyHandle, level, info)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,28 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrConnect2 : Samr.SamrConnect2
{
public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle
) : base(server, access, policyHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,28 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrConnect4 : Samr.SamrConnect4
{
public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle
) : base(server, 2, access, policyHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,28 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
{
public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle
aliasHandle) : base(handle, access, rid, aliasHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,28 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain
{
public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle
domainHandle) : base(handle, access, sid, domainHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}

View File

@ -0,0 +1,55 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcShareEnum : Srvsvc.ShareEnumAll
{
internal class MsrpcShareInfo1 : SmbShareInfo
{
internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1)
{
this._enclosing = enclosing;
NetName = info1.Netname;
Type = info1.Type;
Remark = info1.Remark;
}
private readonly MsrpcShareEnum _enclosing;
}
public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1
(), -1, 0, 0)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
public virtual IFileEntry[] GetEntries()
{
Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info;
MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr
.Count];
for (int i = 0; i < ctr.Count; i++)
{
entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]);
}
return entries;
}
}
}

View File

@ -0,0 +1,43 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
{
public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename
, 502, new Srvsvc.ShareInfo502())
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual Ace[] GetSecurity()
{
Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
if (info502.SecurityDescriptor != null)
{
SecurityDescriptor sd;
sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
return sd.Aces;
}
return null;
}
}
}

View File

@ -0,0 +1,616 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc.Msrpc
{
public class Netdfs
{
public static string GetSyntax()
{
return "4fc742e0-4a10-11cf-8273-00aa004ae673:3.0";
}
public const int DfsVolumeFlavorStandalone = unchecked(0x100);
public const int DfsVolumeFlavorAdBlob = unchecked(0x200);
public const int DfsStorageStateOffline = unchecked(0x0001);
public const int DfsStorageStateOnline = unchecked(0x0002);
public const int DfsStorageStateActive = unchecked(0x0004);
public class DfsInfo1 : NdrObject
{
public string EntryPath;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(EntryPath, 1);
if (EntryPath != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(EntryPath);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int entryPathp = src.Dec_ndr_long();
if (entryPathp != 0)
{
src = src.Deferred;
EntryPath = src.Dec_ndr_string();
}
}
}
public class DfsEnumArray1 : NdrObject
{
public int Count;
public DfsInfo1[] S;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(S, 1);
if (S != null)
{
dst = dst.Deferred;
int ss = Count;
dst.Enc_ndr_long(ss);
int si = dst.Index;
dst.Advance(4 * ss);
dst = dst.Derive(si);
for (int i = 0; i < ss; i++)
{
S[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int sp = src.Dec_ndr_long();
if (sp != 0)
{
src = src.Deferred;
int ss = src.Dec_ndr_long();
int si = src.Index;
src.Advance(4 * ss);
if (S == null)
{
if (ss < 0 || ss > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
S = new DfsInfo1[ss];
}
src = src.Derive(si);
for (int i = 0; i < ss; i++)
{
if (S[i] == null)
{
S[i] = new DfsInfo1();
}
S[i].Decode(src);
}
}
}
}
public class DfsStorageInfo : NdrObject
{
public int State;
public string ServerName;
public string ShareName;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(State);
dst.Enc_ndr_referent(ServerName, 1);
dst.Enc_ndr_referent(ShareName, 1);
if (ServerName != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(ServerName);
}
if (ShareName != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(ShareName);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
State = src.Dec_ndr_long();
int serverNamep = src.Dec_ndr_long();
int shareNamep = src.Dec_ndr_long();
if (serverNamep != 0)
{
src = src.Deferred;
ServerName = src.Dec_ndr_string();
}
if (shareNamep != 0)
{
src = src.Deferred;
ShareName = src.Dec_ndr_string();
}
}
}
public class DfsInfo3 : NdrObject
{
public string Path;
public string Comment;
public int State;
public int NumStores;
public DfsStorageInfo[] Stores;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(Path, 1);
dst.Enc_ndr_referent(Comment, 1);
dst.Enc_ndr_long(State);
dst.Enc_ndr_long(NumStores);
dst.Enc_ndr_referent(Stores, 1);
if (Path != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Path);
}
if (Comment != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Comment);
}
if (Stores != null)
{
dst = dst.Deferred;
int storess = NumStores;
dst.Enc_ndr_long(storess);
int storesi = dst.Index;
dst.Advance(12 * storess);
dst = dst.Derive(storesi);
for (int i = 0; i < storess; i++)
{
Stores[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int pathp = src.Dec_ndr_long();
int commentp = src.Dec_ndr_long();
State = src.Dec_ndr_long();
NumStores = src.Dec_ndr_long();
int storesp = src.Dec_ndr_long();
if (pathp != 0)
{
src = src.Deferred;
Path = src.Dec_ndr_string();
}
if (commentp != 0)
{
src = src.Deferred;
Comment = src.Dec_ndr_string();
}
if (storesp != 0)
{
src = src.Deferred;
int storess = src.Dec_ndr_long();
int storesi = src.Index;
src.Advance(12 * storess);
if (Stores == null)
{
if (storess < 0 || storess > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Stores = new DfsStorageInfo[storess];
}
src = src.Derive(storesi);
for (int i = 0; i < storess; i++)
{
if (Stores[i] == null)
{
Stores[i] = new DfsStorageInfo();
}
Stores[i].Decode(src);
}
}
}
}
public class DfsEnumArray3 : NdrObject
{
public int Count;
public DfsInfo3[] S;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(S, 1);
if (S != null)
{
dst = dst.Deferred;
int ss = Count;
dst.Enc_ndr_long(ss);
int si = dst.Index;
dst.Advance(20 * ss);
dst = dst.Derive(si);
for (int i = 0; i < ss; i++)
{
S[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int sp = src.Dec_ndr_long();
if (sp != 0)
{
src = src.Deferred;
int ss = src.Dec_ndr_long();
int si = src.Index;
src.Advance(20 * ss);
if (S == null)
{
if (ss < 0 || ss > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
S = new DfsInfo3[ss];
}
src = src.Derive(si);
for (int i = 0; i < ss; i++)
{
if (S[i] == null)
{
S[i] = new DfsInfo3();
}
S[i].Decode(src);
}
}
}
}
public class DfsInfo200 : NdrObject
{
public string DfsName;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(DfsName, 1);
if (DfsName != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(DfsName);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int dfsNamep = src.Dec_ndr_long();
if (dfsNamep != 0)
{
src = src.Deferred;
DfsName = src.Dec_ndr_string();
}
}
}
public class DfsEnumArray200 : NdrObject
{
public int Count;
public DfsInfo200[] S;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(S, 1);
if (S != null)
{
dst = dst.Deferred;
int ss = Count;
dst.Enc_ndr_long(ss);
int si = dst.Index;
dst.Advance(4 * ss);
dst = dst.Derive(si);
for (int i = 0; i < ss; i++)
{
S[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int sp = src.Dec_ndr_long();
if (sp != 0)
{
src = src.Deferred;
int ss = src.Dec_ndr_long();
int si = src.Index;
src.Advance(4 * ss);
if (S == null)
{
if (ss < 0 || ss > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
S = new DfsInfo200[ss];
}
src = src.Derive(si);
for (int i = 0; i < ss; i++)
{
if (S[i] == null)
{
S[i] = new DfsInfo200();
}
S[i].Decode(src);
}
}
}
}
public class DfsInfo300 : NdrObject
{
public int Flags;
public string DfsName;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Flags);
dst.Enc_ndr_referent(DfsName, 1);
if (DfsName != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(DfsName);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Flags = src.Dec_ndr_long();
int dfsNamep = src.Dec_ndr_long();
if (dfsNamep != 0)
{
src = src.Deferred;
DfsName = src.Dec_ndr_string();
}
}
}
public class DfsEnumArray300 : NdrObject
{
public int Count;
public DfsInfo300[] S;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(S, 1);
if (S != null)
{
dst = dst.Deferred;
int ss = Count;
dst.Enc_ndr_long(ss);
int si = dst.Index;
dst.Advance(8 * ss);
dst = dst.Derive(si);
for (int i = 0; i < ss; i++)
{
S[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int sp = src.Dec_ndr_long();
if (sp != 0)
{
src = src.Deferred;
int ss = src.Dec_ndr_long();
int si = src.Index;
src.Advance(8 * ss);
if (S == null)
{
if (ss < 0 || ss > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
S = new DfsInfo300[ss];
}
src = src.Derive(si);
for (int i = 0; i < ss; i++)
{
if (S[i] == null)
{
S[i] = new DfsInfo300();
}
S[i].Decode(src);
}
}
}
}
public class DfsEnumStruct : NdrObject
{
public int Level;
public NdrObject E;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Level);
int descr = Level;
dst.Enc_ndr_long(descr);
dst.Enc_ndr_referent(E, 1);
if (E != null)
{
dst = dst.Deferred;
E.Encode(dst);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Level = src.Dec_ndr_long();
src.Dec_ndr_long();
int ep = src.Dec_ndr_long();
if (ep != 0)
{
if (E == null)
{
E = new DfsEnumArray1();
}
src = src.Deferred;
E.Decode(src);
}
}
}
public class NetrDfsEnumEx : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x15);
}
public int Retval;
public string DfsName;
public int Level;
public int Prefmaxlen;
public DfsEnumStruct Info;
public NdrLong Totalentries;
public NetrDfsEnumEx(string dfsName, int level, int prefmaxlen, DfsEnumStruct
info, NdrLong totalentries)
{
this.DfsName = dfsName;
this.Level = level;
this.Prefmaxlen = prefmaxlen;
this.Info = info;
this.Totalentries = totalentries;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_string(DfsName);
dst.Enc_ndr_long(Level);
dst.Enc_ndr_long(Prefmaxlen);
dst.Enc_ndr_referent(Info, 1);
if (Info != null)
{
Info.Encode(dst);
}
dst.Enc_ndr_referent(Totalentries, 1);
if (Totalentries != null)
{
Totalentries.Encode(dst);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
int infop = src.Dec_ndr_long();
if (infop != 0)
{
if (Info == null)
{
Info = new DfsEnumStruct();
}
Info.Decode(src);
}
int totalentriesp = src.Dec_ndr_long();
if (totalentriesp != 0)
{
Totalentries.Decode(src);
}
Retval = src.Dec_ndr_long();
}
}
}
}

View File

@ -0,0 +1,579 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc.Msrpc
{
public class Samr
{
public static string GetSyntax()
{
return "12345778-1234-abcd-ef00-0123456789ac:1.0";
}
public const int AcbDisabled = 1;
public const int AcbHomdirreq = 2;
public const int AcbPwnotreq = 4;
public const int AcbTempdup = 8;
public const int AcbNormal = 16;
public const int AcbMns = 32;
public const int AcbDomtrust = 64;
public const int AcbWstrust = 128;
public const int AcbSvrtrust = 256;
public const int AcbPwnoexp = 512;
public const int AcbAutolock = 1024;
public const int AcbEncTxtPwdAllowed = 2048;
public const int AcbSmartcardRequired = 4096;
public const int AcbTrustedForDelegation = 8192;
public const int AcbNotDelegated = 16384;
public const int AcbUseDesKeyOnly = 32768;
public const int AcbDontRequirePreauth = 65536;
public class SamrCloseHandle : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x01);
}
public int Retval;
public Rpc.PolicyHandle Handle;
public SamrCloseHandle(Rpc.PolicyHandle handle)
{
this.Handle = handle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
Handle.Encode(dst);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
Retval = src.Dec_ndr_long();
}
}
public class SamrConnect2 : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x39);
}
public int Retval;
public string SystemName;
public int AccessMask;
public Rpc.PolicyHandle Handle;
public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle
)
{
this.SystemName = systemName;
this.AccessMask = accessMask;
this.Handle = handle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(SystemName, 1);
if (SystemName != null)
{
dst.Enc_ndr_string(SystemName);
}
dst.Enc_ndr_long(AccessMask);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
Handle.Decode(src);
Retval = src.Dec_ndr_long();
}
}
public class SamrConnect4 : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x3e);
}
public int Retval;
public string SystemName;
public int Unknown;
public int AccessMask;
public Rpc.PolicyHandle Handle;
public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle
handle)
{
this.SystemName = systemName;
this.Unknown = unknown;
this.AccessMask = accessMask;
this.Handle = handle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(SystemName, 1);
if (SystemName != null)
{
dst.Enc_ndr_string(SystemName);
}
dst.Enc_ndr_long(Unknown);
dst.Enc_ndr_long(AccessMask);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
Handle.Decode(src);
Retval = src.Dec_ndr_long();
}
}
public class SamrOpenDomain : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x07);
}
public int Retval;
public Rpc.PolicyHandle Handle;
public int AccessMask;
public Rpc.SidT Sid;
public Rpc.PolicyHandle DomainHandle;
public SamrOpenDomain(Rpc.PolicyHandle handle, int accessMask, Rpc.SidT sid, Rpc.PolicyHandle
domainHandle)
{
this.Handle = handle;
this.AccessMask = accessMask;
this.Sid = sid;
this.DomainHandle = domainHandle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
Handle.Encode(dst);
dst.Enc_ndr_long(AccessMask);
Sid.Encode(dst);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
DomainHandle.Decode(src);
Retval = src.Dec_ndr_long();
}
}
public class SamrSamEntry : NdrObject
{
public int Idx;
public Rpc.Unicode_string Name;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Idx);
dst.Enc_ndr_short(Name.Length);
dst.Enc_ndr_short(Name.MaximumLength);
dst.Enc_ndr_referent(Name.Buffer, 1);
if (Name.Buffer != null)
{
dst = dst.Deferred;
int nameBufferl = Name.Length / 2;
int nameBuffers = Name.MaximumLength / 2;
dst.Enc_ndr_long(nameBuffers);
dst.Enc_ndr_long(0);
dst.Enc_ndr_long(nameBufferl);
int nameBufferi = dst.Index;
dst.Advance(2 * nameBufferl);
dst = dst.Derive(nameBufferi);
for (int i = 0; i < nameBufferl; i++)
{
dst.Enc_ndr_short(Name.Buffer[i]);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Idx = src.Dec_ndr_long();
src.Align(4);
if (Name == null)
{
Name = new Rpc.Unicode_string();
}
Name.Length = (short)src.Dec_ndr_short();
Name.MaximumLength = (short)src.Dec_ndr_short();
int nameBufferp = src.Dec_ndr_long();
if (nameBufferp != 0)
{
src = src.Deferred;
int nameBuffers = src.Dec_ndr_long();
src.Dec_ndr_long();
int nameBufferl = src.Dec_ndr_long();
int nameBufferi = src.Index;
src.Advance(2 * nameBufferl);
if (Name.Buffer == null)
{
if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Name.Buffer = new short[nameBuffers];
}
src = src.Derive(nameBufferi);
for (int i = 0; i < nameBufferl; i++)
{
Name.Buffer[i] = (short)src.Dec_ndr_short();
}
}
}
}
public class SamrSamArray : NdrObject
{
public int Count;
public SamrSamEntry[] Entries;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(Entries, 1);
if (Entries != null)
{
dst = dst.Deferred;
int entriess = Count;
dst.Enc_ndr_long(entriess);
int entriesi = dst.Index;
dst.Advance(12 * entriess);
dst = dst.Derive(entriesi);
for (int i = 0; i < entriess; i++)
{
Entries[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int entriesp = src.Dec_ndr_long();
if (entriesp != 0)
{
src = src.Deferred;
int entriess = src.Dec_ndr_long();
int entriesi = src.Index;
src.Advance(12 * entriess);
if (Entries == null)
{
if (entriess < 0 || entriess > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Entries = new SamrSamEntry[entriess];
}
src = src.Derive(entriesi);
for (int i = 0; i < entriess; i++)
{
if (Entries[i] == null)
{
Entries[i] = new SamrSamEntry();
}
Entries[i].Decode(src);
}
}
}
}
public class SamrEnumerateAliasesInDomain : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x0f);
}
public int Retval;
public Rpc.PolicyHandle DomainHandle;
public int ResumeHandle;
public int AcctFlags;
public SamrSamArray Sam;
public int NumEntries;
public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, int resumeHandle
, int acctFlags, SamrSamArray sam, int numEntries)
{
this.DomainHandle = domainHandle;
this.ResumeHandle = resumeHandle;
this.AcctFlags = acctFlags;
this.Sam = sam;
this.NumEntries = numEntries;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
DomainHandle.Encode(dst);
dst.Enc_ndr_long(ResumeHandle);
dst.Enc_ndr_long(AcctFlags);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
ResumeHandle = src.Dec_ndr_long();
int samp = src.Dec_ndr_long();
if (samp != 0)
{
if (Sam == null)
{
Sam = new SamrSamArray();
}
Sam.Decode(src);
}
NumEntries = src.Dec_ndr_long();
Retval = src.Dec_ndr_long();
}
}
public class SamrOpenAlias : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x1b);
}
public int Retval;
public Rpc.PolicyHandle DomainHandle;
public int AccessMask;
public int Rid;
public Rpc.PolicyHandle AliasHandle;
public SamrOpenAlias(Rpc.PolicyHandle domainHandle, int accessMask, int rid, Rpc.PolicyHandle
aliasHandle)
{
this.DomainHandle = domainHandle;
this.AccessMask = accessMask;
this.Rid = rid;
this.AliasHandle = aliasHandle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
DomainHandle.Encode(dst);
dst.Enc_ndr_long(AccessMask);
dst.Enc_ndr_long(Rid);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
AliasHandle.Decode(src);
Retval = src.Dec_ndr_long();
}
}
public class SamrGetMembersInAlias : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x21);
}
public int Retval;
public Rpc.PolicyHandle AliasHandle;
public Lsarpc.LsarSidArray Sids;
public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray
sids)
{
this.AliasHandle = aliasHandle;
this.Sids = sids;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
AliasHandle.Encode(dst);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
Sids.Decode(src);
Retval = src.Dec_ndr_long();
}
}
public const int SeGroupMandatory = 1;
public const int SeGroupEnabledByDefault = 2;
public const int SeGroupEnabled = 4;
public const int SeGroupOwner = 8;
public const int SeGroupUseForDenyOnly = 16;
public const int SeGroupResource = 536870912;
public const int SeGroupLogonId = -1073741824;
public class SamrRidWithAttribute : NdrObject
{
public int Rid;
public int Attributes;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Rid);
dst.Enc_ndr_long(Attributes);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Rid = src.Dec_ndr_long();
Attributes = src.Dec_ndr_long();
}
}
public class SamrRidWithAttributeArray : NdrObject
{
public int Count;
public SamrRidWithAttribute[] Rids;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(Rids, 1);
if (Rids != null)
{
dst = dst.Deferred;
int ridss = Count;
dst.Enc_ndr_long(ridss);
int ridsi = dst.Index;
dst.Advance(8 * ridss);
dst = dst.Derive(ridsi);
for (int i = 0; i < ridss; i++)
{
Rids[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int ridsp = src.Dec_ndr_long();
if (ridsp != 0)
{
src = src.Deferred;
int ridss = src.Dec_ndr_long();
int ridsi = src.Index;
src.Advance(8 * ridss);
if (Rids == null)
{
if (ridss < 0 || ridss > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Rids = new SamrRidWithAttribute[ridss];
}
src = src.Derive(ridsi);
for (int i = 0; i < ridss; i++)
{
if (Rids[i] == null)
{
Rids[i] = new SamrRidWithAttribute();
}
Rids[i].Decode(src);
}
}
}
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class SamrAliasHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access
, int rid)
{
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -0,0 +1,41 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class SamrDomainHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access
, Rpc.SidT sid)
{
MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this
);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -0,0 +1,49 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class SamrPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this);
try
{
handle.Sendrecv(rpc);
}
catch (DcerpcException de)
{
if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError)
{
throw;
}
MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this);
handle.Sendrecv(rpc2);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -0,0 +1,734 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc.Msrpc
{
public class Srvsvc
{
public static string GetSyntax()
{
return "4b324fc8-1670-01d3-1278-5a47bf6ee188:3.0";
}
public class ShareInfo0 : NdrObject
{
public string Netname;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(Netname, 1);
if (Netname != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Netname);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int netnamep = src.Dec_ndr_long();
if (netnamep != 0)
{
src = src.Deferred;
Netname = src.Dec_ndr_string();
}
}
}
public class ShareInfoCtr0 : NdrObject
{
public int Count;
public ShareInfo0[] Array;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(Array, 1);
if (Array != null)
{
dst = dst.Deferred;
int arrays = Count;
dst.Enc_ndr_long(arrays);
int arrayi = dst.Index;
dst.Advance(4 * arrays);
dst = dst.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
Array[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int arrayp = src.Dec_ndr_long();
if (arrayp != 0)
{
src = src.Deferred;
int arrays = src.Dec_ndr_long();
int arrayi = src.Index;
src.Advance(4 * arrays);
if (Array == null)
{
if (arrays < 0 || arrays > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Array = new ShareInfo0[arrays];
}
src = src.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
if (Array[i] == null)
{
Array[i] = new ShareInfo0();
}
Array[i].Decode(src);
}
}
}
}
public class ShareInfo1 : NdrObject
{
public string Netname;
public int Type;
public string Remark;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(Netname, 1);
dst.Enc_ndr_long(Type);
dst.Enc_ndr_referent(Remark, 1);
if (Netname != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Netname);
}
if (Remark != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Remark);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int netnamep = src.Dec_ndr_long();
Type = src.Dec_ndr_long();
int remarkp = src.Dec_ndr_long();
if (netnamep != 0)
{
src = src.Deferred;
Netname = src.Dec_ndr_string();
}
if (remarkp != 0)
{
src = src.Deferred;
Remark = src.Dec_ndr_string();
}
}
}
public class ShareInfoCtr1 : NdrObject
{
public int Count;
public ShareInfo1[] Array;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(Array, 1);
if (Array != null)
{
dst = dst.Deferred;
int arrays = Count;
dst.Enc_ndr_long(arrays);
int arrayi = dst.Index;
dst.Advance(12 * arrays);
dst = dst.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
Array[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int arrayp = src.Dec_ndr_long();
if (arrayp != 0)
{
src = src.Deferred;
int arrays = src.Dec_ndr_long();
int arrayi = src.Index;
src.Advance(12 * arrays);
if (Array == null)
{
if (arrays < 0 || arrays > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Array = new ShareInfo1[arrays];
}
src = src.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
if (Array[i] == null)
{
Array[i] = new ShareInfo1();
}
Array[i].Decode(src);
}
}
}
}
public class ShareInfo502 : NdrObject
{
public string Netname;
public int Type;
public string Remark;
public int Permissions;
public int MaxUses;
public int CurrentUses;
public string Path;
public string Password;
public int SdSize;
public byte[] SecurityDescriptor;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_referent(Netname, 1);
dst.Enc_ndr_long(Type);
dst.Enc_ndr_referent(Remark, 1);
dst.Enc_ndr_long(Permissions);
dst.Enc_ndr_long(MaxUses);
dst.Enc_ndr_long(CurrentUses);
dst.Enc_ndr_referent(Path, 1);
dst.Enc_ndr_referent(Password, 1);
dst.Enc_ndr_long(SdSize);
dst.Enc_ndr_referent(SecurityDescriptor, 1);
if (Netname != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Netname);
}
if (Remark != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Remark);
}
if (Path != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Path);
}
if (Password != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Password);
}
if (SecurityDescriptor != null)
{
dst = dst.Deferred;
int securityDescriptors = SdSize;
dst.Enc_ndr_long(securityDescriptors);
int securityDescriptori = dst.Index;
dst.Advance(1 * securityDescriptors);
dst = dst.Derive(securityDescriptori);
for (int i = 0; i < securityDescriptors; i++)
{
dst.Enc_ndr_small(SecurityDescriptor[i]);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int netnamep = src.Dec_ndr_long();
Type = src.Dec_ndr_long();
int remarkp = src.Dec_ndr_long();
Permissions = src.Dec_ndr_long();
MaxUses = src.Dec_ndr_long();
CurrentUses = src.Dec_ndr_long();
int pathp = src.Dec_ndr_long();
int passwordp = src.Dec_ndr_long();
SdSize = src.Dec_ndr_long();
int securityDescriptorp = src.Dec_ndr_long();
if (netnamep != 0)
{
src = src.Deferred;
Netname = src.Dec_ndr_string();
}
if (remarkp != 0)
{
src = src.Deferred;
Remark = src.Dec_ndr_string();
}
if (pathp != 0)
{
src = src.Deferred;
Path = src.Dec_ndr_string();
}
if (passwordp != 0)
{
src = src.Deferred;
Password = src.Dec_ndr_string();
}
if (securityDescriptorp != 0)
{
src = src.Deferred;
int securityDescriptors = src.Dec_ndr_long();
int securityDescriptori = src.Index;
src.Advance(1 * securityDescriptors);
if (SecurityDescriptor == null)
{
if (securityDescriptors < 0 || securityDescriptors > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
SecurityDescriptor = new byte[securityDescriptors];
}
src = src.Derive(securityDescriptori);
for (int i = 0; i < securityDescriptors; i++)
{
SecurityDescriptor[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
}
public class ShareInfoCtr502 : NdrObject
{
public int Count;
public ShareInfo502[] Array;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Count);
dst.Enc_ndr_referent(Array, 1);
if (Array != null)
{
dst = dst.Deferred;
int arrays = Count;
dst.Enc_ndr_long(arrays);
int arrayi = dst.Index;
dst.Advance(40 * arrays);
dst = dst.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
Array[i].Encode(dst);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Count = src.Dec_ndr_long();
int arrayp = src.Dec_ndr_long();
if (arrayp != 0)
{
src = src.Deferred;
int arrays = src.Dec_ndr_long();
int arrayi = src.Index;
src.Advance(40 * arrays);
if (Array == null)
{
if (arrays < 0 || arrays > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Array = new ShareInfo502[arrays];
}
src = src.Derive(arrayi);
for (int i = 0; i < arrays; i++)
{
if (Array[i] == null)
{
Array[i] = new ShareInfo502();
}
Array[i].Decode(src);
}
}
}
}
public class ShareEnumAll : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x0f);
}
public int Retval;
public string Servername;
public int Level;
public NdrObject Info;
public int Prefmaxlen;
public int Totalentries;
public int ResumeHandle;
public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen,
int totalentries, int resumeHandle)
{
this.Servername = servername;
this.Level = level;
this.Info = info;
this.Prefmaxlen = prefmaxlen;
this.Totalentries = totalentries;
this.ResumeHandle = resumeHandle;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(Servername, 1);
if (Servername != null)
{
dst.Enc_ndr_string(Servername);
}
dst.Enc_ndr_long(Level);
int descr = Level;
dst.Enc_ndr_long(descr);
dst.Enc_ndr_referent(Info, 1);
if (Info != null)
{
dst = dst.Deferred;
Info.Encode(dst);
}
dst.Enc_ndr_long(Prefmaxlen);
dst.Enc_ndr_long(ResumeHandle);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
Level = src.Dec_ndr_long();
src.Dec_ndr_long();
int infop = src.Dec_ndr_long();
if (infop != 0)
{
if (Info == null)
{
Info = new ShareInfoCtr0();
}
src = src.Deferred;
Info.Decode(src);
}
Totalentries = src.Dec_ndr_long();
ResumeHandle = src.Dec_ndr_long();
Retval = src.Dec_ndr_long();
}
}
public class ShareGetInfo : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x10);
}
public int Retval;
public string Servername;
public string Sharename;
public int Level;
public NdrObject Info;
public ShareGetInfo(string servername, string sharename, int level, NdrObject info
)
{
this.Servername = servername;
this.Sharename = sharename;
this.Level = level;
this.Info = info;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(Servername, 1);
if (Servername != null)
{
dst.Enc_ndr_string(Servername);
}
dst.Enc_ndr_string(Sharename);
dst.Enc_ndr_long(Level);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
src.Dec_ndr_long();
int infop = src.Dec_ndr_long();
if (infop != 0)
{
if (Info == null)
{
Info = new ShareInfo0();
}
src = src.Deferred;
Info.Decode(src);
}
Retval = src.Dec_ndr_long();
}
}
public class ServerInfo100 : NdrObject
{
public int PlatformId;
public string Name;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(PlatformId);
dst.Enc_ndr_referent(Name, 1);
if (Name != null)
{
dst = dst.Deferred;
dst.Enc_ndr_string(Name);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
PlatformId = src.Dec_ndr_long();
int namep = src.Dec_ndr_long();
if (namep != 0)
{
src = src.Deferred;
Name = src.Dec_ndr_string();
}
}
}
public class ServerGetInfo : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x15);
}
public int Retval;
public string Servername;
public int Level;
public NdrObject Info;
public ServerGetInfo(string servername, int level, NdrObject info)
{
this.Servername = servername;
this.Level = level;
this.Info = info;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(Servername, 1);
if (Servername != null)
{
dst.Enc_ndr_string(Servername);
}
dst.Enc_ndr_long(Level);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
src.Dec_ndr_long();
int infop = src.Dec_ndr_long();
if (infop != 0)
{
if (Info == null)
{
Info = new ServerInfo100();
}
src = src.Deferred;
Info.Decode(src);
}
Retval = src.Dec_ndr_long();
}
}
public class TimeOfDayInfo : NdrObject
{
public int Elapsedt;
public int Msecs;
public int Hours;
public int Mins;
public int Secs;
public int Hunds;
public int Timezone;
public int Tinterval;
public int Day;
public int Month;
public int Year;
public int Weekday;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Elapsedt);
dst.Enc_ndr_long(Msecs);
dst.Enc_ndr_long(Hours);
dst.Enc_ndr_long(Mins);
dst.Enc_ndr_long(Secs);
dst.Enc_ndr_long(Hunds);
dst.Enc_ndr_long(Timezone);
dst.Enc_ndr_long(Tinterval);
dst.Enc_ndr_long(Day);
dst.Enc_ndr_long(Month);
dst.Enc_ndr_long(Year);
dst.Enc_ndr_long(Weekday);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Elapsedt = src.Dec_ndr_long();
Msecs = src.Dec_ndr_long();
Hours = src.Dec_ndr_long();
Mins = src.Dec_ndr_long();
Secs = src.Dec_ndr_long();
Hunds = src.Dec_ndr_long();
Timezone = src.Dec_ndr_long();
Tinterval = src.Dec_ndr_long();
Day = src.Dec_ndr_long();
Month = src.Dec_ndr_long();
Year = src.Dec_ndr_long();
Weekday = src.Dec_ndr_long();
}
}
public class RemoteTod : DcerpcMessage
{
public override int GetOpnum()
{
return unchecked(0x1c);
}
public int Retval;
public string Servername;
public TimeOfDayInfo Info;
public RemoteTod(string servername, TimeOfDayInfo info)
{
this.Servername = servername;
this.Info = info;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_referent(Servername, 1);
if (Servername != null)
{
dst.Enc_ndr_string(Servername);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
int infop = src.Dec_ndr_long();
if (infop != 0)
{
if (Info == null)
{
Info = new TimeOfDayInfo();
}
Info.Decode(src);
}
Retval = src.Dec_ndr_long();
}
}
}
}

View File

@ -0,0 +1,305 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrBuffer
{
internal int Referent;
internal Hashtable Referents;
internal class Entry
{
internal int Referent;
internal object Obj;
}
public byte[] Buf;
public int Start;
public int Index;
public int Length;
public NdrBuffer Deferred;
public NdrBuffer(byte[] buf, int start)
{
this.Buf = buf;
this.Start = Index = start;
Length = 0;
Deferred = this;
}
public virtual NdrBuffer Derive(int idx)
{
NdrBuffer nb = new NdrBuffer(Buf, Start);
nb.Index = idx;
nb.Deferred = Deferred;
return nb;
}
public virtual void Reset()
{
Index = Start;
Length = 0;
Deferred = this;
}
public virtual int GetIndex()
{
return Index;
}
public virtual void SetIndex(int index)
{
this.Index = index;
}
public virtual int GetCapacity()
{
return Buf.Length - Start;
}
public virtual int GetTailSpace()
{
return Buf.Length - Index;
}
public virtual byte[] GetBuffer()
{
return Buf;
}
public virtual int Align(int boundary, byte value)
{
int n = Align(boundary);
int i = n;
while (i > 0)
{
Buf[Index - i] = value;
i--;
}
return n;
}
public virtual void WriteOctetArray(byte[] b, int i, int l)
{
Array.Copy(b, i, Buf, Index, l);
Advance(l);
}
public virtual void ReadOctetArray(byte[] b, int i, int l)
{
Array.Copy(Buf, Index, b, i, l);
Advance(l);
}
public virtual int GetLength()
{
return Deferred.Length;
}
public virtual void SetLength(int length)
{
Deferred.Length = length;
}
public virtual void Advance(int n)
{
Index += n;
if ((Index - Start) > Deferred.Length)
{
Deferred.Length = Index - Start;
}
}
public virtual int Align(int boundary)
{
int m = boundary - 1;
int i = Index - Start;
int n = ((i + m) & ~m) - i;
Advance(n);
return n;
}
public virtual void Enc_ndr_small(int s)
{
Buf[Index] = unchecked((byte)(s & unchecked(0xFF)));
Advance(1);
}
public virtual int Dec_ndr_small()
{
int val = Buf[Index] & unchecked(0xFF);
Advance(1);
return val;
}
public virtual void Enc_ndr_short(int s)
{
Align(2);
Encdec.Enc_uint16le((short)s, Buf, Index);
Advance(2);
}
public virtual int Dec_ndr_short()
{
Align(2);
int val = Encdec.Dec_uint16le(Buf, Index);
Advance(2);
return val;
}
public virtual void Enc_ndr_long(int l)
{
Align(4);
Encdec.Enc_uint32le(l, Buf, Index);
Advance(4);
}
public virtual int Dec_ndr_long()
{
Align(4);
int val = Encdec.Dec_uint32le(Buf, Index);
Advance(4);
return val;
}
public virtual void Enc_ndr_hyper(long h)
{
Align(8);
Encdec.Enc_uint64le(h, Buf, Index);
Advance(8);
}
public virtual long Dec_ndr_hyper()
{
Align(8);
long val = Encdec.Dec_uint64le(Buf, Index);
Advance(8);
return val;
}
public virtual void Enc_ndr_string(string s)
{
Align(4);
int i = Index;
int len = s.Length;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
Encdec.Enc_uint32le(0, Buf, i);
i += 4;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
try
{
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len
* 2);
}
catch (UnsupportedEncodingException)
{
}
i += len * 2;
Buf[i++] = unchecked((byte)('\0'));
Buf[i++] = unchecked((byte)('\0'));
Advance(i - Index);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public virtual string Dec_ndr_string()
{
Align(4);
int i = Index;
string val = null;
int len = Encdec.Dec_uint32le(Buf, i);
i += 12;
if (len != 0)
{
len--;
int size = len * 2;
try
{
if (size < 0 || size > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE");
i += size + 2;
}
catch (UnsupportedEncodingException)
{
}
}
Advance(i - Index);
return val;
}
private int GetDceReferent(object obj)
{
Entry e;
if (Referents == null)
{
Referents = new Hashtable();
Referent = 1;
}
if ((e = (Entry)Referents.Get(obj)) == null)
{
e = new Entry();
e.Referent = Referent++;
e.Obj = obj;
Referents.Put(obj, e);
}
return e.Referent;
}
public virtual void Enc_ndr_referent(object obj, int type)
{
if (obj == null)
{
Enc_ndr_long(0);
return;
}
switch (type)
{
case 1:
case 3:
{
Enc_ndr_long(Runtime.IdentityHashCode(obj));
return;
}
case 2:
{
Enc_ndr_long(GetDceReferent(obj));
return;
}
}
}
public override string ToString()
{
return "start=" + Start + ",index=" + Index + ",length=" + GetLength();
}
}
}

View File

@ -0,0 +1,32 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrException : IOException
{
public static readonly string NoNullRef = "ref pointer cannot be null";
public static readonly string InvalidConformance = "invalid array conformance";
public NdrException(string msg) : base(msg)
{
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrHyper : NdrObject
{
public long Value;
public NdrHyper(long value)
{
this.Value = value;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_hyper(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_hyper();
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrLong : NdrObject
{
public int Value;
public NdrLong(int value)
{
this.Value = value;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_long(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_long();
}
}
}

View File

@ -0,0 +1,27 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public abstract class NdrObject
{
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode(NdrBuffer dst);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode(NdrBuffer src);
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrShort : NdrObject
{
public int Value;
public NdrShort(int value)
{
this.Value = value & unchecked(0xFF);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_short(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_short();
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrSmall : NdrObject
{
public int Value;
public NdrSmall(int value)
{
this.Value = value & unchecked(0xFF);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_small(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_small();
}
}
}

View File

@ -0,0 +1,285 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public class Rpc
{
public class UuidT : NdrObject
{
public int TimeLow;
public short TimeMid;
public short TimeHiAndVersion;
public byte ClockSeqHiAndReserved;
public byte ClockSeqLow;
public byte[] Node;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(TimeLow);
dst.Enc_ndr_short(TimeMid);
dst.Enc_ndr_short(TimeHiAndVersion);
dst.Enc_ndr_small(ClockSeqHiAndReserved);
dst.Enc_ndr_small(ClockSeqLow);
int nodes = 6;
int nodei = dst.Index;
dst.Advance(1 * nodes);
dst = dst.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
dst.Enc_ndr_small(Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
TimeLow = src.Dec_ndr_long();
TimeMid = (short)src.Dec_ndr_short();
TimeHiAndVersion = (short)src.Dec_ndr_short();
ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int nodes = 6;
int nodei = src.Index;
src.Advance(1 * nodes);
if (Node == null)
{
if (nodes < 0 || nodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Node = new byte[nodes];
}
src = src.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
public class PolicyHandle : NdrObject
{
public int Type;
public UuidT Uuid;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Type);
dst.Enc_ndr_long(Uuid.TimeLow);
dst.Enc_ndr_short(Uuid.TimeMid);
dst.Enc_ndr_short(Uuid.TimeHiAndVersion);
dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved);
dst.Enc_ndr_small(Uuid.ClockSeqLow);
int uuidNodes = 6;
int uuidNodei = dst.Index;
dst.Advance(1 * uuidNodes);
dst = dst.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
dst.Enc_ndr_small(Uuid.Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Type = src.Dec_ndr_long();
src.Align(4);
if (Uuid == null)
{
Uuid = new UuidT();
}
Uuid.TimeLow = src.Dec_ndr_long();
Uuid.TimeMid = (short)src.Dec_ndr_short();
Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int uuidNodes = 6;
int uuidNodei = src.Index;
src.Advance(1 * uuidNodes);
if (Uuid.Node == null)
{
if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Uuid.Node = new byte[uuidNodes];
}
src = src.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
public class Unicode_string : NdrObject
{
public short Length;
public short MaximumLength;
public short[] Buffer;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_short(Length);
dst.Enc_ndr_short(MaximumLength);
dst.Enc_ndr_referent(Buffer, 1);
if (Buffer != null)
{
dst = dst.Deferred;
int bufferl = Length / 2;
int buffers = MaximumLength / 2;
dst.Enc_ndr_long(buffers);
dst.Enc_ndr_long(0);
dst.Enc_ndr_long(bufferl);
int bufferi = dst.Index;
dst.Advance(2 * bufferl);
dst = dst.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
dst.Enc_ndr_short(Buffer[i]);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Length = (short)src.Dec_ndr_short();
MaximumLength = (short)src.Dec_ndr_short();
int bufferp = src.Dec_ndr_long();
if (bufferp != 0)
{
src = src.Deferred;
int buffers = src.Dec_ndr_long();
src.Dec_ndr_long();
int bufferl = src.Dec_ndr_long();
int bufferi = src.Index;
src.Advance(2 * bufferl);
if (Buffer == null)
{
if (buffers < 0 || buffers > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Buffer = new short[buffers];
}
src = src.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
Buffer[i] = (short)src.Dec_ndr_short();
}
}
}
}
public class SidT : NdrObject
{
public byte Revision;
public byte SubAuthorityCount;
public byte[] IdentifierAuthority;
public int[] SubAuthority;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
int subAuthoritys = SubAuthorityCount;
dst.Enc_ndr_long(subAuthoritys);
dst.Enc_ndr_small(Revision);
dst.Enc_ndr_small(SubAuthorityCount);
int identifierAuthoritys = 6;
int identifierAuthorityi = dst.Index;
dst.Advance(1 * identifierAuthoritys);
int subAuthorityi = dst.Index;
dst.Advance(4 * subAuthoritys);
dst = dst.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
dst.Enc_ndr_small(IdentifierAuthority[i]);
}
dst = dst.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
dst.Enc_ndr_long(SubAuthority[i1]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int subAuthoritys = src.Dec_ndr_long();
Revision = unchecked((byte)src.Dec_ndr_small());
SubAuthorityCount = unchecked((byte)src.Dec_ndr_small());
int identifierAuthoritys = 6;
int identifierAuthorityi = src.Index;
src.Advance(1 * identifierAuthoritys);
int subAuthorityi = src.Index;
src.Advance(4 * subAuthoritys);
if (IdentifierAuthority == null)
{
if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
IdentifierAuthority = new byte[identifierAuthoritys];
}
src = src.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small());
}
if (SubAuthority == null)
{
if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
SubAuthority = new int[subAuthoritys];
}
src = src.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
SubAuthority[i1] = src.Dec_ndr_long();
}
}
}
}
}

View File

@ -0,0 +1,148 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
namespace SharpCifs.Dcerpc
{
public class Uuid : Rpc.UuidT
{
public static int Hex_to_bin(char[] arr, int offset, int length)
{
int value = 0;
int ai;
int count;
count = 0;
for (ai = offset; ai < arr.Length && count < length; ai++)
{
value <<= 4;
switch (arr[ai])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
value += arr[ai] - '0';
break;
}
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
{
value += 10 + (arr[ai] - 'A');
break;
}
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
{
value += 10 + (arr[ai] - 'a');
break;
}
default:
{
throw new ArgumentException(new string(arr, offset, length));
}
}
count++;
}
return value;
}
internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static string Bin_to_hex(int value, int length)
{
char[] arr = new char[length];
int ai = arr.Length;
while (ai-- > 0)
{
arr[ai] = Hexchars[value & unchecked(0xF)];
value = (int)(((uint)value) >> 4);
}
return new string(arr);
}
private static byte B(int i)
{
return unchecked((byte)(i & unchecked(0xFF)));
}
private static short S(int i)
{
return (short)(i & unchecked(0xFFFF));
}
public Uuid(Rpc.UuidT uuid)
{
TimeLow = uuid.TimeLow;
TimeMid = uuid.TimeMid;
TimeHiAndVersion = uuid.TimeHiAndVersion;
ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved;
ClockSeqLow = uuid.ClockSeqLow;
Node = new byte[6];
Node[0] = uuid.Node[0];
Node[1] = uuid.Node[1];
Node[2] = uuid.Node[2];
Node[3] = uuid.Node[3];
Node[4] = uuid.Node[4];
Node[5] = uuid.Node[5];
}
public Uuid(string str)
{
char[] arr = str.ToCharArray();
TimeLow = Hex_to_bin(arr, 0, 8);
TimeMid = S(Hex_to_bin(arr, 9, 4));
TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4));
ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2));
ClockSeqLow = B(Hex_to_bin(arr, 21, 2));
Node = new byte[6];
Node[0] = B(Hex_to_bin(arr, 24, 2));
Node[1] = B(Hex_to_bin(arr, 26, 2));
Node[2] = B(Hex_to_bin(arr, 28, 2));
Node[3] = B(Hex_to_bin(arr, 30, 2));
Node[4] = B(Hex_to_bin(arr, 32, 2));
Node[5] = B(Hex_to_bin(arr, 34, 2));
}
public override string ToString()
{
return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex
(TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex
(ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex
(Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node
[5], 2);
}
}
}

View File

@ -0,0 +1,65 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public class UnicodeString : Rpc.Unicode_string
{
internal bool Zterm;
public UnicodeString(bool zterm)
{
this.Zterm = zterm;
}
public UnicodeString(Rpc.Unicode_string rus, bool zterm)
{
Length = rus.Length;
MaximumLength = rus.MaximumLength;
Buffer = rus.Buffer;
this.Zterm = zterm;
}
public UnicodeString(string str, bool zterm)
{
this.Zterm = zterm;
int len = str.Length;
int zt = zterm ? 1 : 0;
Length = MaximumLength = (short)((len + zt) * 2);
Buffer = new short[len + zt];
int i;
for (i = 0; i < len; i++)
{
Buffer[i] = (short)str[i];
}
if (zterm)
{
Buffer[i] = 0;
}
}
public override string ToString()
{
int len = Length / 2 - (Zterm ? 1 : 0);
char[] ca = new char[len];
for (int i = 0; i < len; i++)
{
ca[i] = (char)Buffer[i];
}
return new string(ca, 0, len);
}
}
}

View File

@ -0,0 +1,202 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Smb;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class Lmhosts
{
private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"
);
private static readonly Hashtable Tab = new Hashtable();
private static long _lastModified = 1L;
private static int _alt;
private static LogStream _log = LogStream.GetInstance();
/// <summary>
/// This is really just for
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
/// . It does
/// not throw an
/// <see cref="UnknownHostException">Sharpen.UnknownHostException</see>
/// because this
/// is queried frequently and exceptions would be rather costly to
/// throw on a regular basis here.
/// </summary>
public static NbtAddress GetByName(string host)
{
lock (typeof(Lmhosts))
{
return GetByName(new Name(host, 0x20, null));
}
}
internal static NbtAddress GetByName(Name name)
{
lock (typeof(Lmhosts))
{
NbtAddress result = null;
try
{
if (Filename != null)
{
FilePath f = new FilePath(Filename);
long lm;
if ((lm = f.LastModified()) > _lastModified)
{
_lastModified = lm;
Tab.Clear();
_alt = 0;
//path -> fileStream
//Populate(new FileReader(f));
Populate(new FileReader(new FileStream(f, FileMode.Open)));
}
result = (NbtAddress)Tab[name];
}
}
catch (FileNotFoundException fnfe)
{
if (_log.Level > 1)
{
_log.WriteLine("lmhosts file: " + Filename);
Runtime.PrintStackTrace(fnfe, _log);
}
}
catch (IOException ioe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ioe, _log);
}
}
return result;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal static void Populate(StreamReader r)
{
string line;
BufferedReader br = new BufferedReader((InputStreamReader)r);
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.Length == 0)
{
}
else
{
if (line[0] == '#')
{
if (line.StartsWith("#INCLUDE "))
{
line = Runtime.Substring(line, line.IndexOf('\\'));
string url = "smb:" + line.Replace('\\', '/');
if (_alt > 0)
{
try
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
catch (IOException ioe)
{
_log.WriteLine("lmhosts URL: " + url);
Runtime.PrintStackTrace(ioe, _log);
continue;
}
_alt--;
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.StartsWith("#END_ALTERNATE"))
{
break;
}
}
}
else
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
}
else
{
if (line.StartsWith("#BEGIN_ALTERNATE"))
{
_alt++;
}
else
{
if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
{
_alt--;
throw new IOException("no lmhosts alternate includes loaded");
}
}
}
}
else
{
if (char.IsDigit(line[0]))
{
char[] data = line.ToCharArray();
int ip;
int i;
int j;
Name name;
NbtAddress addr;
char c;
c = '.';
ip = i = 0;
for (; i < data.Length && c == '.'; i++)
{
int b = unchecked(0x00);
for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
{
b = b * 10 + c - '0';
}
ip = (ip << 8) + b;
}
while (i < data.Length && char.IsWhiteSpace(data[i]))
{
i++;
}
j = i;
while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
{
j++;
}
name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
);
addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
, NbtAddress.UnknownMacAddress);
Tab.Put(name, addr);
}
}
}
}
}
}
}

View File

@ -0,0 +1,269 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Text;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class Name
{
private const int TypeOffset = 31;
private const int ScopeOffset = 33;
private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope"
);
internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding"
, Runtime.GetProperty("file.encoding"));
public string name;
public string Scope;
public int HexCode;
internal int SrcHashCode;
public Name()
{
}
public Name(string name, int hexCode, string scope)
{
if (name.Length > 15)
{
name = Runtime.Substring(name, 0, 15);
}
this.name = name.ToUpper();
this.HexCode = hexCode;
this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope;
SrcHashCode = 0;
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
// write 0x20 in first byte
dst[dstIndex] = unchecked(0x20);
// write name
try
{
byte[] tmp = Runtime.GetBytesForString(name, OemEncoding
);
int i;
for (i = 0; i < tmp.Length; i++)
{
dst[dstIndex + (2 * i + 1)] = unchecked((byte)(((tmp[i] & unchecked(0xF0))
>> 4) + unchecked(0x41)));
dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F))
+ unchecked(0x41)));
}
for (; i < 15; i++)
{
dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43));
dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41));
}
dst[dstIndex + TypeOffset] = unchecked((byte)(((HexCode & unchecked(0xF0)
) >> 4) + unchecked(0x41)));
dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
}
catch (UnsupportedEncodingException)
{
}
return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset);
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
byte[] tmp = new byte[ScopeOffset];
int length = 15;
for (int i = 0; i < 15; i++)
{
tmp[i] = unchecked((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF))
- unchecked(0x41)) << 4));
tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF)
) - unchecked(0x41)) & unchecked(0x0F)));
if (tmp[i] != unchecked((byte)' '))
{
length = i + 1;
}
}
try
{
name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding
);
}
catch (UnsupportedEncodingException)
{
}
HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(
0x41)) & unchecked(0x0F);
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
}
internal int ReadWireFormatDos(byte[] src, int srcIndex)
{
int length = 15;
byte[] tmp = new byte[length];
Array.Copy(src, srcIndex, tmp, 0, length);
try
{
name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
}
catch (Exception ex)
{
}
HexCode = src[srcIndex + length];
return length + 1;
}
internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex)
{
if (Scope == null)
{
dst[dstIndex] = unchecked(unchecked(0x00));
return 1;
}
// copy new scope in
dst[dstIndex++] = unchecked((byte)('.'));
try
{
Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding
), 0, dst, dstIndex, Scope.Length);
}
catch (UnsupportedEncodingException)
{
}
dstIndex += Scope.Length;
dst[dstIndex++] = unchecked(unchecked(0x00));
// now go over scope backwards converting '.' to label length
int i = dstIndex - 2;
int e = i - Scope.Length;
int c = 0;
do
{
if (dst[i] == '.')
{
dst[i] = unchecked((byte)c);
c = 0;
}
else
{
c++;
}
}
while (i-- > e);
return Scope.Length + 2;
}
internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int n;
StringBuilder sb;
if ((n = src[srcIndex++] & unchecked(0xFF)) == 0)
{
Scope = null;
return 1;
}
try
{
sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
while ((n = src[srcIndex++] & unchecked(0xFF)) != 0)
{
sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
}
Scope = sb.ToString();
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
public override int GetHashCode()
{
int result;
result = name.GetHashCode();
result += 65599 * HexCode;
result += 65599 * SrcHashCode;
if (Scope != null && Scope.Length != 0)
{
result += Scope.GetHashCode();
}
return result;
}
public override bool Equals(object obj)
{
Name n;
if (!(obj is Name))
{
return false;
}
n = (Name)obj;
if (Scope == null && n.Scope == null)
{
return name.Equals(n.name) && HexCode == n.HexCode;
}
return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
//return "";
string n = name;
// fix MSBROWSE name
if (n == null)
{
n = "null";
}
else
{
if (n[0] == unchecked(0x01))
{
char[] c = n.ToCharArray();
c[0] = '.';
c[1] = '.';
c[14] = '.';
n = new string(c);
}
}
sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">");
if (Scope != null)
{
sb.Append(".").Append(Scope);
}
return sb.ToString();
}
}
}

View File

@ -0,0 +1,52 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NameQueryRequest : NameServicePacket
{
internal NameQueryRequest(Name name)
{
QuestionName = name;
QuestionType = Nb;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return WriteQuestionSectionWireFormat(dst, dstIndex);
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadQuestionSectionWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
public override string ToString()
{
return "NameQueryRequest[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,68 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NameQueryResponse : NameServicePacket
{
public NameQueryResponse()
{
RecordName = new Name();
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
if (ResultCode != 0 || OpCode != Query)
{
return 0;
}
bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5;
srcIndex += 2;
int address = ReadInt4(src, srcIndex);
if (address != 0)
{
AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType);
}
else
{
AddrEntry[AddrIndex] = null;
}
return 6;
}
public override string ToString()
{
return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry
+ "]";
}
}
}

View File

@ -0,0 +1,660 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Threading;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
using Thread = SharpCifs.Util.Sharpen.Thread;
namespace SharpCifs.Netbios
{
internal class NameServiceClient : IRunnable
{
internal const int DefaultSoTimeout = 5000;
internal const int DefaultRcvBufSize = 576;
internal const int DefaultSndBufSize = 576;
internal const int NameServiceUdpPort = 137;
internal const int DefaultRetryCount = 2;
internal const int DefaultRetryTimeout = 3000;
internal const int ResolverLmhosts = 1;
internal const int ResolverBcast = 2;
internal const int ResolverWins = 3;
private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size"
, DefaultSndBufSize);
private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size"
, DefaultRcvBufSize);
private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout",
DefaultSoTimeout);
private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount"
, DefaultRetryCount);
private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout"
, DefaultRetryTimeout);
private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137);
private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr"
, null);
private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder");
private static LogStream _log = LogStream.GetInstance();
private readonly object _lock = new object();
private int _lport;
private int _closeTimeout;
private byte[] _sndBuf;
private byte[] _rcvBuf;
private SocketEx _socket;
private Hashtable _responseTable = new Hashtable();
private Thread _thread;
private int _nextNameTrnId;
private int[] _resolveOrder;
private bool _waitResponse = true;
private AutoResetEvent _autoResetWaitReceive;
internal IPAddress laddr;
internal IPAddress Baddr;
public NameServiceClient()
: this(Lport, Laddr)
{
}
internal NameServiceClient(int lport, IPAddress laddr)
{
this._lport = lport;
this.laddr = laddr
?? Config.GetLocalHost()
?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();
try
{
Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
}
catch (Exception ex)
{
}
_sndBuf = new byte[SndBufSize];
_rcvBuf = new byte[RcvBufSize];
if (string.IsNullOrEmpty(Ro))
{
if (NbtAddress.GetWinsAddress() == null)
{
_resolveOrder = new int[2];
_resolveOrder[0] = ResolverLmhosts;
_resolveOrder[1] = ResolverBcast;
}
else
{
_resolveOrder = new int[3];
_resolveOrder[0] = ResolverLmhosts;
_resolveOrder[1] = ResolverWins;
_resolveOrder[2] = ResolverBcast;
}
}
else
{
int[] tmp = new int[3];
StringTokenizer st = new StringTokenizer(Ro, ",");
int i = 0;
while (st.HasMoreTokens())
{
string s = st.NextToken().Trim();
if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
{
tmp[i++] = ResolverLmhosts;
}
else
{
if (Runtime.EqualsIgnoreCase(s, "WINS"))
{
if (NbtAddress.GetWinsAddress() == null)
{
if (_log.Level > 1)
{
_log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
);
}
continue;
}
tmp[i++] = ResolverWins;
}
else
{
if (Runtime.EqualsIgnoreCase(s, "BCAST"))
{
tmp[i++] = ResolverBcast;
}
else
{
if (Runtime.EqualsIgnoreCase(s, "DNS"))
{
}
else
{
// skip
if (_log.Level > 1)
{
_log.WriteLine("unknown resolver method: " + s);
}
}
}
}
}
}
_resolveOrder = new int[i];
Array.Copy(tmp, 0, _resolveOrder, 0, i);
}
}
internal virtual int GetNextNameTrnId()
{
if ((++_nextNameTrnId & unchecked(0xFFFF)) == 0)
{
_nextNameTrnId = 1;
}
return _nextNameTrnId;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual void EnsureOpen(int timeout)
{
_closeTimeout = 0;
if (SoTimeout != 0)
{
_closeTimeout = Math.Max(SoTimeout, timeout);
}
// If socket is still good, the new closeTimeout will
// be ignored; see tryClose comment.
if (_socket == null)
{
_socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IPAddress.`Address` property deleted
//_socket.Bind(new IPEndPoint(laddr.Address, _lport));
_socket.Bind(new IPEndPoint(laddr, _lport));
if (_waitResponse)
{
_thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
_thread.SetDaemon(true);
_thread.Start();
}
}
}
internal virtual void TryClose()
{
lock (_lock)
{
if (_socket != null)
{
//Socket.`Close` method deleted
//_socket.Close();
_socket.Dispose();
_socket = null;
}
_thread = null;
if (_waitResponse)
{
_responseTable.Clear();
} else
{
_autoResetWaitReceive.Set();
}
}
}
public virtual void Run()
{
int nameTrnId;
NameServicePacket response;
try
{
while (_thread == Thread.CurrentThread())
{
_socket.SoTimeOut = _closeTimeout;
int len = _socket.Receive(_rcvBuf, 0, RcvBufSize);
if (_log.Level > 3)
{
_log.WriteLine("NetBIOS: new data read from socket");
}
nameTrnId = NameServicePacket.ReadNameTrnId(_rcvBuf, 0);
response = (NameServicePacket)_responseTable.Get(nameTrnId);
if (response == null || response.Received)
{
continue;
}
lock (response)
{
response.ReadWireFormat(_rcvBuf, 0);
if (_log.Level > 3)
{
_log.WriteLine(response);
Hexdump.ToHexdump(_log, _rcvBuf, 0, len);
}
if (response.IsResponse)
{
response.Received = true;
Runtime.Notify(response);
}
}
}
}
catch (TimeoutException) { }
catch (Exception ex)
{
if (_log.Level > 2)
{
Runtime.PrintStackTrace(ex, _log);
}
}
finally
{
TryClose();
}
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual void Send(NameServicePacket request, NameServicePacket response,
int timeout)
{
int nid = 0;
int max = NbtAddress.Nbns.Length;
if (max == 0)
{
max = 1;
}
lock (response)
{
while (max-- > 0)
{
try
{
lock (_lock)
{
request.NameTrnId = GetNextNameTrnId();
nid = request.NameTrnId;
response.Received = false;
_responseTable.Put(nid, response);
EnsureOpen(timeout + 1000);
int requestLenght = request.WriteWireFormat(_sndBuf, 0);
_socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
if (_log.Level > 3)
{
_log.WriteLine(request);
Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
}
}
if (_waitResponse)
{
long start = Runtime.CurrentTimeMillis();
while (timeout > 0)
{
Runtime.Wait(response, timeout);
if (response.Received && request.QuestionType == response.RecordType)
{
return;
}
response.Received = false;
timeout -= (int)(Runtime.CurrentTimeMillis() - start);
}
}
}
catch (Exception ie)
{
throw new IOException(ie.Message);
}
finally
{
//Sharpen.Collections.Remove(responseTable, nid);
if (_waitResponse)
{
_responseTable.Remove(nid);
}
}
if (_waitResponse)
{
lock (_lock)
{
if (NbtAddress.IsWins(request.Addr) == false)
{
break;
}
if (request.Addr == NbtAddress.GetWinsAddress())
{
NbtAddress.SwitchWins();
}
request.Addr = NbtAddress.GetWinsAddress();
}
}
}
}
}
/// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
{
int n;
NameQueryRequest request = new NameQueryRequest(name);
NameQueryResponse response = new NameQueryResponse();
request.Addr = addr ?? NbtAddress.GetWinsAddress();
request.IsBroadcast = request.Addr == null;
if (request.IsBroadcast)
{
request.Addr = Baddr;
n = RetryCount;
}
else
{
request.IsBroadcast = false;
n = 1;
}
do
{
try
{
Send(request, response, RetryTimeout);
}
catch (IOException ioe)
{
if (_log.Level > 1)
{
Runtime.PrintStackTrace(ioe, _log);
}
throw new UnknownHostException(ioe);
}
if (response.Received && response.ResultCode == 0)
{
return response.AddrEntry;
}
}
while (--n > 0 && request.IsBroadcast);
throw new UnknownHostException();
}
/// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress GetByName(Name name, IPAddress addr)
{
int n;
NameQueryRequest request = new NameQueryRequest(name);
NameQueryResponse response = new NameQueryResponse();
if (addr != null)
{
request.Addr = addr;
request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked(unchecked(0xFF)));
n = RetryCount;
do
{
try
{
Send(request, response, RetryTimeout);
}
catch (IOException ioe)
{
if (_log.Level > 1)
{
Runtime.PrintStackTrace(ioe, _log);
}
throw new UnknownHostException(ioe);
}
if (response.Received && response.ResultCode == 0
&& response.IsResponse)
{
int last = response.AddrEntry.Length - 1;
response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode();
return response.AddrEntry[last];
}
}
while (--n > 0 && request.IsBroadcast);
throw new UnknownHostException();
}
for (int i = 0; i < _resolveOrder.Length; i++)
{
try
{
switch (_resolveOrder[i])
{
case ResolverLmhosts:
{
NbtAddress ans = Lmhosts.GetByName(name);
if (ans != null)
{
ans.HostName.SrcHashCode = 0;
// just has to be different
// from other methods
return ans;
}
break;
}
case ResolverWins:
case ResolverBcast:
{
if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName
&& name.HexCode != unchecked(0x1d))
{
request.Addr = NbtAddress.GetWinsAddress();
request.IsBroadcast = false;
}
else
{
request.Addr = Baddr;
request.IsBroadcast = true;
}
n = RetryCount;
while (n-- > 0)
{
try
{
Send(request, response, RetryTimeout);
}
catch (IOException ioe)
{
if (_log.Level > 1)
{
Runtime.PrintStackTrace(ioe, _log);
}
throw new UnknownHostException(ioe);
}
if (response.Received && response.ResultCode == 0
&& response.IsResponse)
{
response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
return response.AddrEntry[0];
}
if (_resolveOrder[i] == ResolverWins)
{
break;
}
}
break;
}
}
}
catch (IOException)
{
}
}
throw new UnknownHostException();
}
/// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
{
int n;
int srcHashCode;
NodeStatusRequest request;
NodeStatusResponse response;
response = new NodeStatusResponse(addr);
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
request.Addr = addr.GetInetAddress();
n = RetryCount;
while (n-- > 0)
{
try
{
Send(request, response, RetryTimeout);
}
catch (IOException ioe)
{
if (_log.Level > 1)
{
Runtime.PrintStackTrace(ioe, _log);
}
throw new UnknownHostException(ioe);
}
if (response.Received && response.ResultCode == 0)
{
srcHashCode = request.Addr.GetHashCode();
for (int i = 0; i < response.AddressArray.Length; i++)
{
response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
}
return response.AddressArray;
}
}
throw new UnknownHostException();
}
internal virtual NbtAddress[] GetHosts()
{
try
{
_waitResponse = false;
byte[] bAddrBytes = laddr.GetAddressBytes();
for (int i = 1; i <= 254; i++)
{
NodeStatusRequest request;
NodeStatusResponse response;
byte[] addrBytes = {
bAddrBytes[0],
bAddrBytes[1],
bAddrBytes[2],
(byte)i
};
IPAddress addr = new IPAddress(addrBytes);
//response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
// (int)addr.Address, false, 0x20));
response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20));
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x20), null));
request.Addr = addr;
Send(request, response, 0);
}
}
catch (IOException ioe)
{
if (_log.Level > 1)
{
Runtime.PrintStackTrace(ioe, _log);
}
throw new UnknownHostException(ioe);
}
_autoResetWaitReceive = new AutoResetEvent(false);
_thread = new Thread(this);
_thread.SetDaemon(true);
_thread.Start();
_autoResetWaitReceive.WaitOne();
List<NbtAddress> result = new List<NbtAddress>();
foreach (var key in _responseTable.Keys)
{
NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key];
if (resp.Received && resp.ResultCode == 0)
{
foreach (var entry in resp.AddressArray)
{
if (entry.HostName.HexCode == 0x20)
{
result.Add(entry);
}
}
}
}
_responseTable.Clear();
_waitResponse = true;
return result.Count > 0 ? result.ToArray() : null;
}
}
}

View File

@ -0,0 +1,448 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.Net;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal abstract class NameServicePacket
{
internal const int Query = 0;
internal const int Wack = 7;
internal const int FmtErr = 0x1;
internal const int SrvErr = 0x2;
internal const int ImpErr = 0x4;
internal const int RfsErr = 0x5;
internal const int ActErr = 0x6;
internal const int CftErr = 0x7;
internal const int NbIn = 0x00200001;
internal const int NbstatIn = 0x00210001;
internal const int Nb = 0x0020;
internal const int Nbstat = 0x0021;
internal const int In = 0x0001;
internal const int A = 0x0001;
internal const int Ns = 0x0002;
internal const int Null = 0x000a;
internal const int HeaderLength = 12;
internal const int OpcodeOffset = 2;
internal const int QuestionOffset = 4;
internal const int AnswerOffset = 6;
internal const int AuthorityOffset = 8;
internal const int AdditionalOffset = 10;
// opcode
// rcode
// type/class
// header field offsets
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
0xFF));
}
internal static int ReadInt4(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
[srcIndex + 3] & unchecked(0xFF));
}
internal static int ReadNameTrnId(byte[] src, int srcIndex)
{
return ReadInt2(src, srcIndex);
}
internal int AddrIndex;
internal NbtAddress[] AddrEntry;
internal int NameTrnId;
internal int OpCode;
internal int ResultCode;
internal int QuestionCount;
internal int AnswerCount;
internal int AuthorityCount;
internal int AdditionalCount;
internal bool Received;
internal bool IsResponse;
internal bool IsAuthAnswer;
internal bool IsTruncated;
internal bool IsRecurDesired;
internal bool IsRecurAvailable;
internal bool IsBroadcast;
internal Name QuestionName;
internal Name RecordName;
internal int QuestionType;
internal int QuestionClass;
internal int RecordType;
internal int RecordClass;
internal int Ttl;
internal int RDataLength;
internal IPAddress Addr;
public NameServicePacket()
{
IsRecurDesired = true;
IsBroadcast = true;
QuestionCount = 1;
QuestionClass = In;
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteBodyWireFormat(dst, dstIndex);
return dstIndex - start;
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += ReadHeaderWireFormat(src, srcIndex);
srcIndex += ReadBodyWireFormat(src, srcIndex);
return srcIndex - start;
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(NameTrnId, dst, dstIndex);
dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer
? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01)
: unchecked(0x00))));
dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked(
0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) :
unchecked(0x00)) + (ResultCode & unchecked(0x0F))));
WriteInt2(QuestionCount, dst, start + QuestionOffset);
WriteInt2(AnswerCount, dst, start + AnswerOffset);
WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
return HeaderLength;
}
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
{
NameTrnId = ReadInt2(src, srcIndex);
IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false
: true;
OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3;
IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ?
false : true;
IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false
: true;
IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ?
false : true;
IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80))
== 0) ? false : true;
IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0)
? false : true;
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
return HeaderLength;
}
internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
WriteInt2(QuestionType, dst, dstIndex);
dstIndex += 2;
WriteInt2(QuestionClass, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
QuestionType = ReadInt2(src, srcIndex);
srcIndex += 2;
QuestionClass = ReadInt2(src, srcIndex);
srcIndex += 2;
return srcIndex - start;
}
internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (RecordName == QuestionName)
{
dst[dstIndex++] = unchecked(unchecked(0xC0));
// label string pointer to
dst[dstIndex++] = unchecked(unchecked(0x0C));
}
else
{
// questionName (offset 12)
dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
}
WriteInt2(RecordType, dst, dstIndex);
dstIndex += 2;
WriteInt2(RecordClass, dst, dstIndex);
dstIndex += 2;
WriteInt4(Ttl, dst, dstIndex);
dstIndex += 4;
RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
WriteInt2(RDataLength, dst, dstIndex);
dstIndex += 2 + RDataLength;
return dstIndex - start;
}
internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int end;
if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
{
RecordName = QuestionName;
// label string pointer to questionName
srcIndex += 2;
}
else
{
srcIndex += RecordName.ReadWireFormat(src, srcIndex);
}
RecordType = ReadInt2(src, srcIndex);
srcIndex += 2;
RecordClass = ReadInt2(src, srcIndex);
srcIndex += 2;
Ttl = ReadInt4(src, srcIndex);
srcIndex += 4;
RDataLength = ReadInt2(src, srcIndex);
srcIndex += 2;
AddrEntry = new NbtAddress[RDataLength / 6];
end = srcIndex + RDataLength;
for (AddrIndex = 0; srcIndex < end; AddrIndex++)
{
srcIndex += ReadRDataWireFormat(src, srcIndex);
}
return srcIndex - start;
}
internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
public override string ToString()
{
string opCodeString;
string resultCodeString;
string questionTypeString;
string recordTypeString;
switch (OpCode)
{
case Query:
{
opCodeString = "QUERY";
break;
}
case Wack:
{
opCodeString = "WACK";
break;
}
default:
{
opCodeString = Extensions.ToString(OpCode);
break;
}
}
switch (ResultCode)
{
case FmtErr:
{
resultCodeString = "FMT_ERR";
break;
}
case SrvErr:
{
resultCodeString = "SRV_ERR";
break;
}
case ImpErr:
{
resultCodeString = "IMP_ERR";
break;
}
case RfsErr:
{
resultCodeString = "RFS_ERR";
break;
}
case ActErr:
{
resultCodeString = "ACT_ERR";
break;
}
case CftErr:
{
resultCodeString = "CFT_ERR";
break;
}
default:
{
resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
break;
}
}
switch (QuestionType)
{
case Nb:
{
questionTypeString = "NB";
break;
}
case Nbstat:
{
questionTypeString = "NBSTAT";
break;
}
default:
{
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
break;
}
}
switch (RecordType)
{
case A:
{
recordTypeString = "A";
break;
}
case Ns:
{
recordTypeString = "NS";
break;
}
case Null:
{
recordTypeString = "NULL";
break;
}
case Nb:
{
recordTypeString = "NB";
break;
}
case Nbstat:
{
recordTypeString = "NBSTAT";
break;
}
default:
{
recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4);
break;
}
}
return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode="
+ opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated
+ ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired
+ ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount="
+ QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount
+ ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType="
+ questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" +
Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType="
+ recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump
.ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength;
}
}
}

View File

@ -0,0 +1,920 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Linq;
using System.Net;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
using Extensions = SharpCifs.Util.Sharpen.Extensions;
namespace SharpCifs.Netbios
{
/// <summary>This class represents a NetBIOS over TCP/IP address.</summary>
/// <remarks>
/// This class represents a NetBIOS over TCP/IP address. Under normal
/// conditions, users of jCIFS need not be concerned with this class as
/// name resolution and session services are handled internally by the smb package.
/// <p> Applications can use the methods <code>getLocalHost</code>,
/// <code>getByName</code>, and
/// <code>getAllByAddress</code> to create a new NbtAddress instance. This
/// class is symmetric with
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
/// .
/// <p><b>About NetBIOS:</b> The NetBIOS name
/// service is a dynamic distributed service that allows hosts to resolve
/// names by broadcasting a query, directing queries to a server such as
/// Samba or WINS. NetBIOS is currently the primary networking layer for
/// providing name service, datagram service, and session service to the
/// Microsoft Windows platform. A NetBIOS name can be 15 characters long
/// and hosts usually registers several names on the network. From a
/// Windows command prompt you can see
/// what names a host registers with the nbtstat command.
/// <p><blockquote><pre>
/// C:\&gt;nbtstat -a 192.168.1.15
/// NetBIOS Remote Machine Name Table
/// Name Type Status
/// ---------------------------------------------
/// JMORRIS2 <00> UNIQUE Registered
/// BILLING-NY <00> GROUP Registered
/// JMORRIS2 <03> UNIQUE Registered
/// JMORRIS2 <20> UNIQUE Registered
/// BILLING-NY <1E> GROUP Registered
/// JMORRIS <03> UNIQUE Registered
/// MAC Address = 00-B0-34-21-FA-3B
/// </blockquote></pre>
/// <p> The hostname of this machine is <code>JMORRIS2</code>. It is
/// a member of the group(a.k.a workgroup and domain) <code>BILLING-NY</code>. To
/// obtain an
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
/// for a host one might do:
/// <pre>
/// InetAddress addr = NbtAddress.getByName( "jmorris2" ).getInetAddress();
/// </pre>
/// <p>From a UNIX platform with Samba installed you can perform similar
/// diagnostics using the <code>nmblookup</code> utility.
/// </remarks>
/// <author>Michael B. Allen</author>
/// <seealso cref="System.Net.IPAddress">System.Net.IPAddress</seealso>
/// <since>jcifs-0.1</since>
public sealed class NbtAddress
{
internal static readonly string AnyHostsName = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
/// <summary>
/// This is a special name for querying the master browser that serves the
/// list of hosts found in "Network Neighborhood".
/// </summary>
/// <remarks>
/// This is a special name for querying the master browser that serves the
/// list of hosts found in "Network Neighborhood".
/// </remarks>
public static readonly string MasterBrowserName = "\u0001\u0002__MSBROWSE__\u0002";
/// <summary>
/// A special generic name specified when connecting to a host for which
/// a name is not known.
/// </summary>
/// <remarks>
/// A special generic name specified when connecting to a host for which
/// a name is not known. Not all servers respond to this name.
/// </remarks>
public static readonly string SmbserverName = "*SMBSERVER ";
/// <summary>A B node only broadcasts name queries.</summary>
/// <remarks>
/// A B node only broadcasts name queries. This is the default if a
/// nameserver such as WINS or Samba is not specified.
/// </remarks>
public const int BNode = 0;
/// <summary>
/// A Point-to-Point node, or P node, unicasts queries to a nameserver
/// only.
/// </summary>
/// <remarks>
/// A Point-to-Point node, or P node, unicasts queries to a nameserver
/// only. Natrually the <code>jcifs.netbios.nameserver</code> property must
/// be set.
/// </remarks>
public const int PNode = 1;
/// <summary>
/// Try Broadcast queries first, then try to resolve the name using the
/// nameserver.
/// </summary>
/// <remarks>
/// Try Broadcast queries first, then try to resolve the name using the
/// nameserver.
/// </remarks>
public const int MNode = 2;
/// <summary>A Hybrid node tries to resolve a name using the nameserver first.</summary>
/// <remarks>
/// A Hybrid node tries to resolve a name using the nameserver first. If
/// that fails use the broadcast address. This is the default if a nameserver
/// is provided. This is the behavior of Microsoft Windows machines.
/// </remarks>
public const int HNode = 3;
internal static readonly IPAddress[] Nbns = Config.GetInetAddressArray("jcifs.netbios.wins"
, ",", new IPAddress[0]);
private static readonly NameServiceClient Client = new NameServiceClient();
private const int DefaultCachePolicy = 30;
private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
, DefaultCachePolicy);
private const int Forever = -1;
private static int _nbnsIndex;
private static readonly Hashtable AddressCache = new Hashtable();
private static readonly Hashtable LookupTable = new Hashtable();
internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null);
internal static readonly NbtAddress UnknownAddress = new NbtAddress
(UnknownName, 0, false, BNode);
internal static readonly byte[] UnknownMacAddress = { unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)) };
internal sealed class CacheEntry
{
internal Name HostName;
internal NbtAddress Address;
internal long Expiration;
internal CacheEntry(Name hostName, NbtAddress address, long expiration)
{
this.HostName = hostName;
this.Address = address;
this.Expiration = expiration;
}
}
internal static NbtAddress Localhost;
static NbtAddress()
{
IPAddress localInetAddress;
string localHostname;
Name localName;
AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
, Forever));
localInetAddress = Client.laddr;
if (localInetAddress == null)
{
try
{
localInetAddress = Extensions.GetAddressByName("127.0.0.1");
}
catch (UnknownHostException)
{
}
}
localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
if (string.IsNullOrEmpty(localHostname))
{
byte[] addr = localInetAddress.GetAddressBytes();
/*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
(int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
(int)(0xFF))), 2);*/
localHostname = "JCIFS_127_0_0_1";
}
localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope"
, null));
Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
, false, false, true, false, UnknownMacAddress);
CacheAddress(localName, Localhost, Forever);
}
internal static void CacheAddress(Name hostName, NbtAddress addr)
{
if (CachePolicy == 0)
{
return;
}
long expiration = -1;
if (CachePolicy != Forever)
{
expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
}
CacheAddress(hostName, addr, expiration);
}
internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
)
{
if (CachePolicy == 0)
{
return;
}
lock (AddressCache)
{
CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
if (entry == null)
{
entry = new CacheEntry(hostName, addr, expiration);
AddressCache.Put(hostName, entry);
}
else
{
entry.Address = addr;
entry.Expiration = expiration;
}
}
}
internal static void CacheAddressArray(NbtAddress[] addrs)
{
if (CachePolicy == 0)
{
return;
}
long expiration = -1;
if (CachePolicy != Forever)
{
expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
}
lock (AddressCache)
{
for (int i = 0; i < addrs.Length; i++)
{
CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName
);
if (entry == null)
{
entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration);
AddressCache.Put(addrs[i].HostName, entry);
}
else
{
entry.Address = addrs[i];
entry.Expiration = expiration;
}
}
}
}
internal static NbtAddress GetCachedAddress(Name hostName)
{
if (CachePolicy == 0)
{
return null;
}
lock (AddressCache)
{
CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
if (entry != null && entry.Expiration < Runtime.CurrentTimeMillis() && entry.Expiration
>= 0)
{
entry = null;
}
return entry != null ? entry.Address : null;
}
}
/// <exception cref="UnknownHostException"></exception>
internal static NbtAddress DoNameQuery(Name name, IPAddress svr)
{
NbtAddress addr;
if (name.HexCode == unchecked(0x1d) && svr == null)
{
svr = Client.Baddr;
}
// bit of a hack but saves a lookup
name.SrcHashCode = svr != null ? svr.GetHashCode() : 0;
addr = GetCachedAddress(name);
if (addr == null)
{
if ((addr = (NbtAddress)CheckLookupTable(name)) == null)
{
try
{
addr = Client.GetByName(name, svr);
}
catch (UnknownHostException)
{
addr = UnknownAddress;
}
finally
{
CacheAddress(name, addr);
UpdateLookupTable(name);
}
}
}
if (addr == UnknownAddress)
{
throw new UnknownHostException(name.ToString());
}
return addr;
}
private static object CheckLookupTable(Name name)
{
object obj;
lock (LookupTable)
{
if (LookupTable.ContainsKey(name) == false)
{
LookupTable.Put(name, name);
return null;
}
while (LookupTable.ContainsKey(name))
{
try
{
Runtime.Wait(LookupTable);
}
catch (Exception)
{
}
}
}
obj = GetCachedAddress(name);
if (obj == null)
{
lock (LookupTable)
{
LookupTable.Put(name, name);
}
}
return obj;
}
private static void UpdateLookupTable(Name name)
{
lock (LookupTable)
{
//Sharpen.Collections.Remove(LOOKUP_TABLE, name);
LookupTable.Remove(name);
Runtime.NotifyAll(LookupTable);
}
}
/// <summary>Retrieves the local host address.</summary>
/// <remarks>Retrieves the local host address.</remarks>
/// <exception cref="UnknownHostException">
/// This is not likely as the IP returned
/// by <code>InetAddress</code> should be available
/// </exception>
public static NbtAddress GetLocalHost()
{
return Localhost;
}
public static NbtAddress[] GetHosts()
{
return new NameServiceClient().GetHosts();
}
public static Name GetLocalName()
{
return Localhost.HostName;
}
/// <summary>Determines the address of a host given it's host name.</summary>
/// <remarks>
/// Determines the address of a host given it's host name. The name can be a NetBIOS name like
/// "freto" or an IP address like "192.168.1.15". It cannot be a DNS name;
/// the analygous
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
/// or
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
/// <code>getByName</code> methods can be used for that.
/// </remarks>
/// <param name="host">hostname to resolve</param>
/// <exception cref="UnknownHostException">if there is an error resolving the name
/// </exception>
public static NbtAddress GetByName(string host)
{
return GetByName(host, unchecked(0x00), null);
}
/// <summary>Determines the address of a host given it's host name.</summary>
/// <remarks>
/// Determines the address of a host given it's host name. NetBIOS
/// names also have a <code>type</code>. Types(aka Hex Codes)
/// are used to distiquish the various services on a host. &lt;a
/// href="../../../nbtcodes.html"&gt;Here</a> is
/// a fairly complete list of NetBIOS hex codes. Scope is not used but is
/// still functional in other NetBIOS products and so for completeness it has been
/// implemented. A <code>scope</code> of <code>null</code> or <code>""</code>
/// signifies no scope.
/// </remarks>
/// <param name="host">the name to resolve</param>
/// <param name="type">the hex code of the name</param>
/// <param name="scope">the scope of the name</param>
/// <exception cref="UnknownHostException">if there is an error resolving the name
/// </exception>
public static NbtAddress GetByName(string host, int type, string scope)
{
return GetByName(host, type, scope, null);
}
/// <exception cref="UnknownHostException"></exception>
public static NbtAddress GetByName(string host, int type, string scope, IPAddress
svr)
{
if (string.IsNullOrEmpty(host))
{
return GetLocalHost();
}
if (!char.IsDigit(host[0]))
{
return DoNameQuery(new Name(host, type, scope), svr);
}
int ip = unchecked(0x00);
int hitDots = 0;
char[] data = host.ToCharArray();
for (int i = 0; i < data.Length; i++)
{
char c = data[i];
if (c < 48 || c > 57)
{
return DoNameQuery(new Name(host, type, scope), svr);
}
int b = unchecked(0x00);
while (c != '.')
{
if (c < 48 || c > 57)
{
return DoNameQuery(new Name(host, type, scope), svr);
}
b = b * 10 + c - '0';
if (++i >= data.Length)
{
break;
}
c = data[i];
}
if (b > unchecked(0xFF))
{
return DoNameQuery(new Name(host, type, scope), svr);
}
ip = (ip << 8) + b;
hitDots++;
}
if (hitDots != 4 || host.EndsWith("."))
{
return DoNameQuery(new Name(host, type, scope), svr);
}
return new NbtAddress(UnknownName, ip, false, BNode);
}
/// <exception cref="UnknownHostException"></exception>
public static NbtAddress[] GetAllByName(string host, int type, string scope, IPAddress
svr)
{
return Client.GetAllByName(new Name(host, type, scope), svr);
}
/// <summary>Retrieve all addresses of a host by it's address.</summary>
/// <remarks>
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
/// have many names for a given IP address. The name and IP address make the
/// NetBIOS address. This provides a way to retrieve the other names for a
/// host with the same IP address.
/// </remarks>
/// <param name="host">hostname to lookup all addresses for</param>
/// <exception cref="UnknownHostException">if there is an error resolving the name
/// </exception>
public static NbtAddress[] GetAllByAddress(string host)
{
return GetAllByAddress(GetByName(host, unchecked(0x00), null));
}
/// <summary>Retrieve all addresses of a host by it's address.</summary>
/// <remarks>
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
/// have many names for a given IP address. The name and IP address make
/// the NetBIOS address. This provides a way to retrieve the other names
/// for a host with the same IP address. See
/// <see cref="GetByName(string)">GetByName(string)</see>
/// for a description of <code>type</code>
/// and <code>scope</code>.
/// </remarks>
/// <param name="host">hostname to lookup all addresses for</param>
/// <param name="type">the hexcode of the name</param>
/// <param name="scope">the scope of the name</param>
/// <exception cref="UnknownHostException">if there is an error resolving the name
/// </exception>
public static NbtAddress[] GetAllByAddress(string host, int type, string scope)
{
return GetAllByAddress(GetByName(host, type, scope));
}
/// <summary>Retrieve all addresses of a host by it's address.</summary>
/// <remarks>
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
/// have many names for a given IP address. The name and IP address make the
/// NetBIOS address. This provides a way to retrieve the other names for a
/// host with the same IP address.
/// </remarks>
/// <param name="addr">the address to query</param>
/// <exception cref="UnknownHostException">if address cannot be resolved</exception>
public static NbtAddress[] GetAllByAddress(NbtAddress addr)
{
try
{
NbtAddress[] addrs = Client.GetNodeStatus(addr);
CacheAddressArray(addrs);
return addrs;
}
catch (UnknownHostException)
{
throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
== 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
+ addr.GetHostAddress());
}
}
public static IPAddress GetWinsAddress()
{
return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
}
public static bool IsWins(IPAddress svr)
{
for (int i = 0; svr != null && i < Nbns.Length; i++)
{
if (svr.GetHashCode() == Nbns[i].GetHashCode())
{
return true;
}
}
return false;
}
internal static IPAddress SwitchWins()
{
_nbnsIndex = (_nbnsIndex + 1) < Nbns.Length ? _nbnsIndex + 1 : 0;
return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
}
internal Name HostName;
internal int Address;
internal int NodeType;
internal bool GroupName;
internal bool isBeingDeleted;
internal bool isInConflict;
internal bool isActive;
internal bool isPermanent;
internal bool IsDataFromNodeStatus;
internal byte[] MacAddress;
internal string CalledName;
internal NbtAddress(Name hostName, int address, bool groupName, int nodeType)
{
this.HostName = hostName;
this.Address = address;
this.GroupName = groupName;
this.NodeType = nodeType;
}
internal NbtAddress(Name hostName, int address, bool groupName, int nodeType, bool
isBeingDeleted, bool isInConflict, bool isActive, bool isPermanent, byte[] macAddress
)
{
this.HostName = hostName;
this.Address = address;
this.GroupName = groupName;
this.NodeType = nodeType;
this.isBeingDeleted = isBeingDeleted;
this.isInConflict = isInConflict;
this.isActive = isActive;
this.isPermanent = isPermanent;
this.MacAddress = macAddress;
IsDataFromNodeStatus = true;
}
public string FirstCalledName()
{
CalledName = HostName.name;
if (char.IsDigit(CalledName[0]))
{
int i;
int len;
int dots;
char[] data;
i = dots = 0;
len = CalledName.Length;
data = CalledName.ToCharArray();
while (i < len && char.IsDigit(data[i++]))
{
if (i == len && dots == 3)
{
// probably an IP address
CalledName = SmbserverName;
break;
}
if (i < len && data[i] == '.')
{
dots++;
i++;
}
}
}
else
{
switch (HostName.HexCode)
{
case unchecked(0x1B):
case unchecked(0x1C):
case unchecked(0x1D):
{
CalledName = SmbserverName;
break;
}
}
}
return CalledName;
}
public string NextCalledName()
{
if (CalledName == HostName.name)
{
CalledName = SmbserverName;
}
else
{
if (CalledName == SmbserverName)
{
NbtAddress[] addrs;
try
{
addrs = Client.GetNodeStatus(this);
if (HostName.HexCode == unchecked(0x1D))
{
for (int i = 0; i < addrs.Length; i++)
{
if (addrs[i].HostName.HexCode == unchecked(0x20))
{
return addrs[i].HostName.name;
}
}
return null;
}
if (IsDataFromNodeStatus)
{
CalledName = null;
return HostName.name;
}
}
catch (UnknownHostException)
{
CalledName = null;
}
}
else
{
CalledName = null;
}
}
return CalledName;
}
/// <exception cref="UnknownHostException"></exception>
internal void CheckData()
{
if (HostName == UnknownName)
{
GetAllByAddress(this);
}
}
/// <exception cref="UnknownHostException"></exception>
internal void CheckNodeStatusData()
{
if (IsDataFromNodeStatus == false)
{
GetAllByAddress(this);
}
}
/// <summary>Determines if the address is a group address.</summary>
/// <remarks>
/// Determines if the address is a group address. This is also
/// known as a workgroup name or group name.
/// </remarks>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public bool IsGroupAddress()
{
CheckData();
return GroupName;
}
/// <summary>Checks the node type of this address.</summary>
/// <remarks>Checks the node type of this address.</remarks>
/// <returns>
///
/// <see cref="BNode">B_NODE</see>
/// ,
/// <see cref="PNode">P_NODE</see>
/// ,
/// <see cref="MNode">M_NODE</see>
/// ,
/// <see cref="HNode">H_NODE</see>
/// </returns>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public int GetNodeType()
{
CheckData();
return NodeType;
}
/// <summary>Determines if this address in the process of being deleted.</summary>
/// <remarks>Determines if this address in the process of being deleted.</remarks>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public bool IsBeingDeleted()
{
CheckNodeStatusData();
return isBeingDeleted;
}
/// <summary>Determines if this address in conflict with another address.</summary>
/// <remarks>Determines if this address in conflict with another address.</remarks>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public bool IsInConflict()
{
CheckNodeStatusData();
return isInConflict;
}
/// <summary>Determines if this address is active.</summary>
/// <remarks>Determines if this address is active.</remarks>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public bool IsActive()
{
CheckNodeStatusData();
return isActive;
}
/// <summary>Determines if this address is set to be permanent.</summary>
/// <remarks>Determines if this address is set to be permanent.</remarks>
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
/// </exception>
public bool IsPermanent()
{
CheckNodeStatusData();
return isPermanent;
}
/// <summary>Retrieves the MAC address of the remote network interface.</summary>
/// <remarks>Retrieves the MAC address of the remote network interface. Samba returns all zeros.
/// </remarks>
/// <returns>the MAC address as an array of six bytes</returns>
/// <exception cref="UnknownHostException">
/// if the host cannot be resolved to
/// determine the MAC address.
/// </exception>
public byte[] GetMacAddress()
{
CheckNodeStatusData();
return MacAddress;
}
/// <summary>The hostname of this address.</summary>
/// <remarks>
/// The hostname of this address. If the hostname is null the local machines
/// IP address is returned.
/// </remarks>
/// <returns>the text representation of the hostname associated with this address</returns>
public string GetHostName()
{
if (HostName == UnknownName)
{
return GetHostAddress();
}
return HostName.name;
}
/// <summary>Returns the raw IP address of this NbtAddress.</summary>
/// <remarks>
/// Returns the raw IP address of this NbtAddress. The result is in network
/// byte order: the highest order byte of the address is in getAddress()[0].
/// </remarks>
/// <returns>a four byte array</returns>
public byte[] GetAddress()
{
byte[] addr = new byte[4];
addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF
)));
addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF
)));
addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF)
));
addr[3] = unchecked((byte)(Address & unchecked(0xFF)));
return addr;
}
/// <summary>To convert this address to an <code>InetAddress</code>.</summary>
/// <remarks>To convert this address to an <code>InetAddress</code>.</remarks>
/// <returns>
/// the
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
/// representation of this address.
/// </returns>
/// <exception cref="UnknownHostException"></exception>
public IPAddress GetInetAddress()
{
return Extensions.GetAddressByName(GetHostAddress());
}
/// <summary>
/// Returns this IP adress as a
/// <see cref="string">string</see>
/// in the form "%d.%d.%d.%d".
/// </summary>
public string GetHostAddress()
{
return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) + "." + (((int)(
((uint)Address) >> 16)) & unchecked(0xFF)) + "." + (((int)(((uint)Address
) >> 8)) & unchecked(0xFF)) + "." + (((int)(((uint)Address) >> 0)) & unchecked(
0xFF));
}
/// <summary>Returned the hex code associated with this name(e.g.</summary>
/// <remarks>Returned the hex code associated with this name(e.g. 0x20 is for the file service)
/// </remarks>
public int GetNameType()
{
return HostName.HexCode;
}
/// <summary>Returns a hashcode for this IP address.</summary>
/// <remarks>
/// Returns a hashcode for this IP address. The hashcode comes from the IP address
/// and is not generated from the string representation. So because NetBIOS nodes
/// can have many names, all names associated with an IP will have the same
/// hashcode.
/// </remarks>
public override int GetHashCode()
{
return Address;
}
/// <summary>Determines if this address is equal two another.</summary>
/// <remarks>
/// Determines if this address is equal two another. Only the IP Addresses
/// are compared. Similar to the
/// <see cref="GetHashCode()">GetHashCode()</see>
/// method, the comparison
/// is based on the integer IP address and not the string representation.
/// </remarks>
public override bool Equals(object obj)
{
return (obj != null) && (obj is NbtAddress) && (((NbtAddress)obj).Address == Address
);
}
/// <summary>
/// Returns the
/// <see cref="string">string</see>
/// representaion of this address.
/// </summary>
public override string ToString()
{
return HostName + "/" + GetHostAddress();
}
}
}

View File

@ -0,0 +1,164 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
namespace SharpCifs.Netbios
{
public class NbtException : IOException
{
public const int Success = 0;
public const int ErrNamSrvc = unchecked(0x01);
public const int ErrSsnSrvc = unchecked(0x02);
public const int FmtErr = unchecked(0x1);
public const int SrvErr = unchecked(0x2);
public const int ImpErr = unchecked(0x4);
public const int RfsErr = unchecked(0x5);
public const int ActErr = unchecked(0x6);
public const int CftErr = unchecked(0x7);
public const int ConnectionRefused = -1;
public const int NotListeningCalled = unchecked(0x80);
public const int NotListeningCalling = unchecked(0x81);
public const int CalledNotPresent = unchecked(0x82);
public const int NoResources = unchecked(0x83);
public const int Unspecified = unchecked(0x8F);
public int ErrorClass;
public int ErrorCode;
// error classes
// name service error codes
// session service error codes
public static string GetErrorString(int errorClass, int errorCode)
{
string result = string.Empty;
switch (errorClass)
{
case Success:
{
result += "SUCCESS";
break;
}
case ErrNamSrvc:
{
result += "ERR_NAM_SRVC/";
switch (errorCode)
{
case FmtErr:
{
result += "FMT_ERR: Format Error";
goto default;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
case ErrSsnSrvc:
{
result += "ERR_SSN_SRVC/";
switch (errorCode)
{
case ConnectionRefused:
{
result += "Connection refused";
break;
}
case NotListeningCalled:
{
result += "Not listening on called name";
break;
}
case NotListeningCalling:
{
result += "Not listening for calling name";
break;
}
case CalledNotPresent:
{
result += "Called name not present";
break;
}
case NoResources:
{
result += "Called name present, but insufficient resources";
break;
}
case Unspecified:
{
result += "Unspecified error";
break;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
default:
{
result += "unknown error class: " + errorClass;
break;
}
}
return result;
}
public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
, errorCode))
{
this.ErrorClass = errorClass;
this.ErrorCode = errorCode;
}
public override string ToString()
{
return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString="
+ GetErrorString(ErrorClass, ErrorCode);
}
}
}

View File

@ -0,0 +1,59 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NodeStatusRequest : NameServicePacket
{
internal NodeStatusRequest(Name name)
{
QuestionName = name;
QuestionType = Nbstat;
IsRecurDesired = false;
IsBroadcast = false;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
int tmp = QuestionName.HexCode;
QuestionName.HexCode = unchecked(0x00);
// type has to be 0x00 for node status
int result = WriteQuestionSectionWireFormat(dst, dstIndex);
QuestionName.HexCode = tmp;
return result;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
public override string ToString()
{
return "NodeStatusRequest[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,140 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal class NodeStatusResponse : NameServicePacket
{
private NbtAddress _queryAddress;
private int _numberOfNames;
private byte[] _macAddress;
private byte[] _stats;
internal NbtAddress[] AddressArray;
internal NodeStatusResponse(NbtAddress queryAddress)
{
this._queryAddress = queryAddress;
RecordName = new Name();
_macAddress = new byte[6];
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
_numberOfNames = src[srcIndex] & unchecked(0xFF);
int namesLength = _numberOfNames * 18;
int statsLength = RDataLength - namesLength - 1;
_numberOfNames = src[srcIndex++] & unchecked(0xFF);
// gotta read the mac first so we can populate addressArray with it
Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6);
srcIndex += ReadNodeNameArray(src, srcIndex);
_stats = new byte[statsLength];
Array.Copy(src, srcIndex, _stats, 0, statsLength);
srcIndex += statsLength;
return srcIndex - start;
}
private int ReadNodeNameArray(byte[] src, int srcIndex)
{
int start = srcIndex;
AddressArray = new NbtAddress[_numberOfNames];
string n;
int hexCode;
string scope = _queryAddress.HostName.Scope;
bool groupName;
int ownerNodeType;
bool isBeingDeleted;
bool isInConflict;
bool isActive;
bool isPermanent;
int j;
bool addrFound = false;
try
{
for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
{
for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
{
}
n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
);
hexCode = src[srcIndex + 15] & unchecked(0xFF);
groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5;
isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false;
isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false;
isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false;
if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
== NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
{
if (_queryAddress.HostName == NbtAddress.UnknownName)
{
_queryAddress.HostName = new Name(n, hexCode, scope);
}
_queryAddress.GroupName = groupName;
_queryAddress.NodeType = ownerNodeType;
_queryAddress.isBeingDeleted = isBeingDeleted;
_queryAddress.isInConflict = isInConflict;
_queryAddress.isActive = isActive;
_queryAddress.isPermanent = isPermanent;
_queryAddress.MacAddress = _macAddress;
_queryAddress.IsDataFromNodeStatus = true;
addrFound = true;
AddressArray[i] = _queryAddress;
}
else
{
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
, groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
_macAddress);
}
}
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
public override string ToString()
{
return "NodeStatusResponse[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,63 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class SessionRequestPacket : SessionServicePacket
{
private Name _calledName;
private Name _callingName;
public SessionRequestPacket()
{
_calledName = new Name();
_callingName = new Name();
}
public SessionRequestPacket(Name calledName, Name callingName)
{
Type = SessionRequest;
this._calledName = calledName;
this._callingName = callingName;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += _calledName.WriteWireFormat(dst, dstIndex);
dstIndex += _callingName.WriteWireFormat(dst, dstIndex);
return dstIndex - start;
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("invalid session request wire format");
}
bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex);
bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex);
return bufferIndex - start;
}
}
}

View File

@ -0,0 +1,54 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal class SessionRetargetResponsePacket : SessionServicePacket
{
private NbtAddress _retargetAddress;
private int _retargetPort;
public SessionRetargetResponsePacket()
{
Type = SessionRetargetResponse;
Length = 6;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("unexpected EOF reading netbios retarget session response");
}
int addr = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
_retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
_retargetPort = ReadInt2(buffer, bufferIndex);
return Length;
}
}
}

View File

@ -0,0 +1,156 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public abstract class SessionServicePacket
{
internal const int SessionMessage = unchecked(0x00);
internal const int SessionRequest = unchecked(0x81);
public const int PositiveSessionResponse = unchecked(0x82);
public const int NegativeSessionResponse = unchecked(0x83);
internal const int SessionRetargetResponse = unchecked(0x84);
internal const int SessionKeepAlive = unchecked(0x85);
internal const int MaxMessageSize = unchecked(0x0001FFFF);
internal const int HeaderLength = 4;
// session service packet types
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
0xFF));
}
internal static int ReadInt4(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
[srcIndex + 3] & unchecked(0xFF));
}
internal static int ReadLength(byte[] src, int srcIndex)
{
srcIndex++;
return ((src[srcIndex++] & unchecked(0x01)) << 16) + ((src[srcIndex++] & unchecked(
0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF));
}
/// <exception cref="System.IO.IOException"></exception>
internal static int Readn(InputStream @in, byte[] b, int off, int len)
{
int i = 0;
int n;
while (i < len)
{
n = @in.Read(b, off + i, len - i);
if (n <= 0)
{
break;
}
i += n;
}
return i;
}
/// <exception cref="System.IO.IOException"></exception>
internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex
)
{
int n;
if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
{
if (n == -1)
{
return -1;
}
throw new IOException("unexpected EOF reading netbios session header");
}
int t = buffer[bufferIndex] & unchecked(0xFF);
return t;
}
internal int Type;
internal int Length;
public virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength);
WriteHeaderWireFormat(dst, dstIndex);
return HeaderLength + Length;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
ReadHeaderWireFormat(@in, buffer, bufferIndex);
return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)Type);
if (Length > unchecked(0x0000FFFF))
{
dst[dstIndex] = unchecked(unchecked(0x01));
}
dstIndex++;
WriteInt2(Length, dst, dstIndex);
return HeaderLength;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
Type = buffer[bufferIndex++] & unchecked(0xFF);
Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) + ReadInt2(buffer
, bufferIndex + 1);
return HeaderLength;
}
internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
/// <exception cref="System.IO.IOException"></exception>
internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
);
}
}

View File

@ -0,0 +1,197 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Ntlmssp
{
/// <summary>Flags used during negotiation of NTLMSSP authentication.</summary>
/// <remarks>Flags used during negotiation of NTLMSSP authentication.</remarks>
public abstract class NtlmFlags
{
/// <summary>Indicates whether Unicode strings are supported or used.</summary>
/// <remarks>Indicates whether Unicode strings are supported or used.</remarks>
public const int NtlmsspNegotiateUnicode = unchecked(0x00000001);
/// <summary>Indicates whether OEM strings are supported or used.</summary>
/// <remarks>Indicates whether OEM strings are supported or used.</remarks>
public const int NtlmsspNegotiateOem = unchecked(0x00000002);
/// <summary>
/// Indicates whether the authentication target is requested from
/// the server.
/// </summary>
/// <remarks>
/// Indicates whether the authentication target is requested from
/// the server.
/// </remarks>
public const int NtlmsspRequestTarget = unchecked(0x00000004);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </remarks>
public const int NtlmsspNegotiateSign = unchecked(0x00000010);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </remarks>
public const int NtlmsspNegotiateSeal = unchecked(0x00000020);
/// <summary>Indicates datagram authentication.</summary>
/// <remarks>Indicates datagram authentication.</remarks>
public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040);
/// <summary>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </summary>
/// <remarks>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </remarks>
public const int NtlmsspNegotiateLmKey = unchecked(0x00000080);
public const int NtlmsspNegotiateNetware = unchecked(0x00000100);
/// <summary>Indicates support for NTLM authentication.</summary>
/// <remarks>Indicates support for NTLM authentication.</remarks>
public const int NtlmsspNegotiateNtlm = unchecked(0x00000200);
/// <summary>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// This is used in the negotation of local authentication.
/// </remarks>
public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000);
/// <summary>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message. This is used in the negotiation of local
/// authentication.
/// </remarks>
public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000);
/// <summary>
/// Sent by the server to indicate that the server and client are
/// on the same machine.
/// </summary>
/// <remarks>
/// Sent by the server to indicate that the server and client are
/// on the same machine. This implies that the server will include
/// a local security context handle in the Type 2 message, for
/// use in local authentication.
/// </remarks>
public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000);
/// <summary>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </summary>
/// <remarks>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </remarks>
public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </remarks>
public const int NtlmsspTargetTypeDomain = unchecked(0x00010000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </remarks>
public const int NtlmsspTargetTypeServer = unchecked(0x00020000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </remarks>
public const int NtlmsspTargetTypeShare = unchecked(0x00040000);
/// <summary>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications.
/// </summary>
/// <remarks>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications. This refers to a
/// particular session security scheme, and is not related to the use
/// of NTLMv2 authentication.
/// </remarks>
public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000);
public const int NtlmsspRequestInitResponse = unchecked(0x00100000);
public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000
);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message. The Target
/// Information block is used in the calculation of the NTLMv2 response.
/// </remarks>
public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000);
/// <summary>Indicates that 128-bit encryption is supported.</summary>
/// <remarks>Indicates that 128-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate128 = unchecked(0x20000000);
public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000);
/// <summary>Indicates that 56-bit encryption is supported.</summary>
/// <remarks>Indicates that 56-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000));
}
}

View File

@ -0,0 +1,140 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
namespace SharpCifs.Ntlmssp
{
/// <summary>Abstract superclass for all NTLMSSP messages.</summary>
/// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
public abstract class NtlmMessage : NtlmFlags
{
/// <summary>The NTLMSSP "preamble".</summary>
/// <remarks>The NTLMSSP "preamble".</remarks>
protected internal static readonly byte[] NtlmsspSignature = { unchecked(
(byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')),
unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte
)('S')), unchecked((byte)('P')), unchecked(0) };
private static readonly string OemEncoding = Config.DefaultOemEncoding;
protected internal static readonly string UniEncoding = "UTF-16LE";
private int _flags;
/// <summary>Returns the flags currently in use for this message.</summary>
/// <remarks>Returns the flags currently in use for this message.</remarks>
/// <returns>
/// An <code>int</code> containing the flags in use for this
/// message.
/// </returns>
public virtual int GetFlags()
{
return _flags;
}
/// <summary>Sets the flags for this message.</summary>
/// <remarks>Sets the flags for this message.</remarks>
/// <param name="flags">The flags for this message.</param>
public virtual void SetFlags(int flags)
{
this._flags = flags;
}
/// <summary>Returns the status of the specified flag.</summary>
/// <remarks>Returns the status of the specified flag.</remarks>
/// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param>
/// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
public virtual bool GetFlag(int flag)
{
return (GetFlags() & flag) != 0;
}
/// <summary>Sets or clears the specified flag.</summary>
/// <remarks>Sets or clears the specified flag.</remarks>
/// <param name="flag">
/// The flag to set/clear (i.e.,
/// <code>NTLMSSP_NEGOTIATE_OEM</code>).
/// </param>
/// <param name="value">
/// Indicates whether to set (<code>true</code>) or
/// clear (<code>false</code>) the specified flag.
/// </param>
public virtual void SetFlag(int flag, bool value)
{
SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff)
) ^ flag)));
}
internal static int ReadULong(byte[] src, int index)
{
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index
+ 3] & unchecked(0xff)) << 24);
}
internal static int ReadUShort(byte[] src, int index)
{
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
}
internal static byte[] ReadSecurityBuffer(byte[] src, int index)
{
int length = ReadUShort(src, index);
int offset = ReadULong(src, index + 4);
byte[] buffer = new byte[length];
Array.Copy(src, offset, buffer, 0, length);
return buffer;
}
internal static void WriteULong(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff)));
dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff)));
}
internal static void WriteUShort(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
}
internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset,
byte[] src)
{
int length = (src != null) ? src.Length : 0;
if (length == 0)
{
return;
}
WriteUShort(dest, offset, length);
WriteUShort(dest, offset + 2, length);
WriteULong(dest, offset + 4, bodyOffset);
Array.Copy(src, 0, dest, bodyOffset, length);
}
internal static string GetOemEncoding()
{
return OemEncoding;
}
/// <summary>Returns the raw byte representation of this message.</summary>
/// <remarks>Returns the raw byte representation of this message.</remarks>
/// <returns>A <code>byte[]</code> containing the raw message material.</returns>
public abstract byte[] ToByteArray();
}
}

View File

@ -0,0 +1,249 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Netbios;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp
{
/// <summary>Represents an NTLMSSP Type-1 message.</summary>
/// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
public class Type1Message : NtlmMessage
{
private static readonly int DefaultFlags;
private static readonly string DefaultDomain;
private static readonly string DefaultWorkstation;
private string _suppliedDomain;
private string _suppliedWorkstation;
static Type1Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
string defaultWorkstation = null;
try
{
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
}
catch (UnknownHostException)
{
}
DefaultWorkstation = defaultWorkstation;
}
/// <summary>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </remarks>
public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation
())
{
}
/// <summary>Creates a Type-1 message with the specified parameters.</summary>
/// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="suppliedDomain">The supplied authentication domain.</param>
/// <param name="suppliedWorkstation">The supplied workstation name.</param>
public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
{
SetFlags(GetDefaultFlags() | flags);
SetSuppliedDomain(suppliedDomain);
if (suppliedWorkstation == null)
{
suppliedWorkstation = GetDefaultWorkstation();
}
SetSuppliedWorkstation(suppliedWorkstation);
}
/// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary>
/// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks>
/// <param name="material">The raw Type-1 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// </exception>
public Type1Message(byte[] material)
{
Parse(material);
}
/// <summary>Returns the supplied authentication domain.</summary>
/// <remarks>Returns the supplied authentication domain.</remarks>
/// <returns>A <code>String</code> containing the supplied domain.</returns>
public virtual string GetSuppliedDomain()
{
return _suppliedDomain;
}
/// <summary>Sets the supplied authentication domain for this message.</summary>
/// <remarks>Sets the supplied authentication domain for this message.</remarks>
/// <param name="suppliedDomain">The supplied domain for this message.</param>
public virtual void SetSuppliedDomain(string suppliedDomain)
{
this._suppliedDomain = suppliedDomain;
}
/// <summary>Returns the supplied workstation name.</summary>
/// <remarks>Returns the supplied workstation name.</remarks>
/// <returns>A <code>String</code> containing the supplied workstation name.</returns>
public virtual string GetSuppliedWorkstation()
{
return _suppliedWorkstation;
}
/// <summary>Sets the supplied workstation name for this message.</summary>
/// <remarks>Sets the supplied workstation name for this message.</remarks>
/// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
{
this._suppliedWorkstation = suppliedWorkstation;
}
public override byte[] ToByteArray()
{
try
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
int flags = GetFlags();
bool hostInfo = false;
byte[] domain = new byte[0];
if (!string.IsNullOrEmpty(suppliedDomain))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
());
}
else
{
flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
}
byte[] workstation = new byte[0];
if (!string.IsNullOrEmpty(suppliedWorkstation))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
());
}
else
{
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff
)));
}
byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16
];
Array.Copy(NtlmsspSignature, 0, type1, 0, 8);
WriteULong(type1, 8, 1);
WriteULong(type1, 12, flags);
if (hostInfo)
{
WriteSecurityBuffer(type1, 16, 32, domain);
WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
}
return type1;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override string ToString()
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
}
/// <summary>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
/// <summary>Returns the default workstation from the current environment.</summary>
/// <remarks>Returns the default workstation from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default workstation.</returns>
public static string GetDefaultWorkstation()
{
return DefaultWorkstation;
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 1)
{
throw new IOException("Not a Type 1 message.");
}
int flags = ReadULong(material, 12);
string suppliedDomain = null;
if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
{
byte[] domain = ReadSecurityBuffer(material, 16);
suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
}
string suppliedWorkstation = null;
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{
byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
());
}
SetFlags(flags);
SetSuppliedDomain(suppliedDomain);
SetSuppliedWorkstation(suppliedWorkstation);
}
}
}

View File

@ -0,0 +1,438 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Netbios;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp
{
/// <summary>Represents an NTLMSSP Type-2 message.</summary>
/// <remarks>Represents an NTLMSSP Type-2 message.</remarks>
public class Type2Message : NtlmMessage
{
private static readonly int DefaultFlags;
private static readonly string DefaultDomain;
private static readonly byte[] DefaultTargetInformation;
private byte[] _challenge;
private string _target;
private byte[] _context;
private byte[] _targetInformation;
static Type2Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
byte[] domain = new byte[0];
if (DefaultDomain != null)
{
try
{
domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding);
}
catch (IOException)
{
}
}
int domainLength = domain.Length;
byte[] server = new byte[0];
try
{
string host = NbtAddress.GetLocalHost().GetHostName();
if (host != null)
{
try
{
server = Runtime.GetBytesForString(host, UniEncoding);
}
catch (IOException)
{
}
}
}
catch (UnknownHostException)
{
}
int serverLength = server.Length;
byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength
> 0 ? serverLength + 4 : 0) + 4];
int offset = 0;
if (domainLength > 0)
{
WriteUShort(targetInfo, offset, 2);
offset += 2;
WriteUShort(targetInfo, offset, domainLength);
offset += 2;
Array.Copy(domain, 0, targetInfo, offset, domainLength);
offset += domainLength;
}
if (serverLength > 0)
{
WriteUShort(targetInfo, offset, 1);
offset += 2;
WriteUShort(targetInfo, offset, serverLength);
offset += 2;
Array.Copy(server, 0, targetInfo, offset, serverLength);
}
DefaultTargetInformation = targetInfo;
}
/// <summary>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </remarks>
public Type2Message() : this(GetDefaultFlags(), null, null)
{
}
/// <summary>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </remarks>
/// <param name="type1">The Type-1 message which this represents a response to.</param>
public Type2Message(Type1Message type1) : this(type1, null, null)
{
}
/// <summary>Creates a Type-2 message in response to the given Type-1 message.</summary>
/// <remarks>Creates a Type-2 message in response to the given Type-1 message.</remarks>
/// <param name="type1">The Type-1 message which this represents a response to.</param>
/// <param name="challenge">The challenge from the domain controller/server.</param>
/// <param name="target">The authentication target.</param>
public Type2Message(Type1Message type1, byte[] challenge, string target) : this(GetDefaultFlags
(type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget
)) ? GetDefaultDomain() : target)
{
}
/// <summary>Creates a Type-2 message with the specified parameters.</summary>
/// <remarks>Creates a Type-2 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="challenge">The challenge from the domain controller/server.</param>
/// <param name="target">The authentication target.</param>
public Type2Message(int flags, byte[] challenge, string target)
{
SetFlags(flags);
SetChallenge(challenge);
SetTarget(target);
if (target != null)
{
SetTargetInformation(GetDefaultTargetInformation());
}
}
/// <summary>Creates a Type-2 message using the given raw Type-2 material.</summary>
/// <remarks>Creates a Type-2 message using the given raw Type-2 material.</remarks>
/// <param name="material">The raw Type-2 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// </exception>
public Type2Message(byte[] material)
{
Parse(material);
}
/// <summary>Returns the challenge for this message.</summary>
/// <remarks>Returns the challenge for this message.</remarks>
/// <returns>A <code>byte[]</code> containing the challenge.</returns>
public virtual byte[] GetChallenge()
{
return _challenge;
}
/// <summary>Sets the challenge for this message.</summary>
/// <remarks>Sets the challenge for this message.</remarks>
/// <param name="challenge">The challenge from the domain controller/server.</param>
public virtual void SetChallenge(byte[] challenge)
{
this._challenge = challenge;
}
/// <summary>Returns the authentication target.</summary>
/// <remarks>Returns the authentication target.</remarks>
/// <returns>A <code>String</code> containing the authentication target.</returns>
public virtual string GetTarget()
{
return _target;
}
/// <summary>Sets the authentication target.</summary>
/// <remarks>Sets the authentication target.</remarks>
/// <param name="target">The authentication target.</param>
public virtual void SetTarget(string target)
{
this._target = target;
}
/// <summary>Returns the target information block.</summary>
/// <remarks>Returns the target information block.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the target information block.
/// The target information block is used by the client to create an
/// NTLMv2 response.
/// </returns>
public virtual byte[] GetTargetInformation()
{
return _targetInformation;
}
/// <summary>Sets the target information block.</summary>
/// <remarks>
/// Sets the target information block.
/// The target information block is used by the client to create
/// an NTLMv2 response.
/// </remarks>
/// <param name="targetInformation">The target information block.</param>
public virtual void SetTargetInformation(byte[] targetInformation)
{
this._targetInformation = targetInformation;
}
/// <summary>Returns the local security context.</summary>
/// <remarks>Returns the local security context.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the local security
/// context. This is used by the client to negotiate local
/// authentication.
/// </returns>
public virtual byte[] GetContext()
{
return _context;
}
/// <summary>Sets the local security context.</summary>
/// <remarks>
/// Sets the local security context. This is used by the client
/// to negotiate local authentication.
/// </remarks>
/// <param name="context">The local security context.</param>
public virtual void SetContext(byte[] context)
{
this._context = context;
}
public override byte[] ToByteArray()
{
try
{
string targetName = GetTarget();
byte[] challenge = GetChallenge();
byte[] context = GetContext();
byte[] targetInformation = GetTargetInformation();
int flags = GetFlags();
byte[] target = new byte[0];
if ((flags & NtlmsspRequestTarget) != 0)
{
if (!string.IsNullOrEmpty(targetName))
{
target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString
(targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper
(), GetOemEncoding());
}
else
{
flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget);
}
}
if (targetInformation != null)
{
flags |= NtlmsspNegotiateTargetInfo;
// empty context is needed for padding when t.i. is supplied.
if (context == null)
{
context = new byte[8];
}
}
int data = 32;
if (context != null)
{
data += 8;
}
if (targetInformation != null)
{
data += 8;
}
byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation
.Length : 0)];
Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
WriteULong(type2, 8, 2);
WriteSecurityBuffer(type2, 12, data, target);
WriteULong(type2, 20, flags);
Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8);
if (context != null)
{
Array.Copy(context, 0, type2, 32, 8);
}
if (targetInformation != null)
{
WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation);
}
return type2;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override string ToString()
{
string target = GetTarget();
byte[] challenge = GetChallenge();
byte[] context = GetContext();
byte[] targetInformation = GetTargetInformation();
return "Type2Message[target=" + target + ",challenge=" + (challenge == null ? "null"
: "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null"
: "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation
== null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" +
Hexdump.ToHexString(GetFlags(), 8) + "]";
}
/// <summary>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags(Type1Message type1)
{
if (type1 == null)
{
return DefaultFlags;
}
int flags = NtlmsspNegotiateNtlm;
int type1Flags = type1.GetFlags();
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem;
if ((type1Flags & NtlmsspRequestTarget) != 0)
{
string domain = GetDefaultDomain();
if (domain != null)
{
flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain;
}
}
return flags;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
public static byte[] GetDefaultTargetInformation()
{
return DefaultTargetInformation;
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 2)
{
throw new IOException("Not a Type 2 message.");
}
int flags = ReadULong(material, 20);
SetFlags(flags);
string target = null;
byte[] bytes = ReadSecurityBuffer(material, 12);
if (bytes.Length != 0)
{
target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode
) != 0) ? UniEncoding : GetOemEncoding());
}
SetTarget(target);
for (int i1 = 24; i1 < 32; i1++)
{
if (material[i1] != 0)
{
byte[] challenge = new byte[8];
Array.Copy(material, 24, challenge, 0, 8);
SetChallenge(challenge);
break;
}
}
int offset = ReadULong(material, 16);
// offset of targetname start
if (offset == 32 || material.Length == 32)
{
return;
}
for (int i2 = 32; i2 < 40; i2++)
{
if (material[i2] != 0)
{
byte[] context = new byte[8];
Array.Copy(material, 32, context, 0, 8);
SetContext(context);
break;
}
}
if (offset == 40 || material.Length == 40)
{
return;
}
bytes = ReadSecurityBuffer(material, 40);
if (bytes.Length != 0)
{
SetTargetInformation(bytes);
}
}
}
}

View File

@ -0,0 +1,677 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.IO;
using SharpCifs.Netbios;
using SharpCifs.Smb;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp
{
/// <summary>Represents an NTLMSSP Type-3 message.</summary>
/// <remarks>Represents an NTLMSSP Type-3 message.</remarks>
public class Type3Message : NtlmMessage
{
internal const long MillisecondsBetween1970And1601 = 11644473600000L;
private static readonly int DefaultFlags;
private static readonly string DefaultDomain;
private static readonly string DefaultUser;
private static readonly string DefaultPassword;
private static readonly string DefaultWorkstation;
private static readonly int LmCompatibility;
//private static readonly SecureRandom RANDOM = new SecureRandom();
private byte[] _lmResponse;
private byte[] _ntResponse;
private string _domain;
private string _user;
private string _workstation;
private byte[] _masterKey;
private byte[] _sessionKey;
static Type3Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
DefaultUser = Config.GetProperty("jcifs.smb.client.username", null);
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null);
string defaultWorkstation = null;
try
{
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
}
catch (UnknownHostException)
{
}
DefaultWorkstation = defaultWorkstation;
LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
}
/// <summary>
/// Creates a Type-3 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-3 message using default values from the current
/// environment.
/// </remarks>
public Type3Message()
{
SetFlags(GetDefaultFlags());
SetDomain(GetDefaultDomain());
SetUser(GetDefaultUser());
SetWorkstation(GetDefaultWorkstation());
}
/// <summary>
/// Creates a Type-3 message in response to the given Type-2 message
/// using default values from the current environment.
/// </summary>
/// <remarks>
/// Creates a Type-3 message in response to the given Type-2 message
/// using default values from the current environment.
/// </remarks>
/// <param name="type2">The Type-2 message which this represents a response to.</param>
public Type3Message(Type2Message type2)
{
SetFlags(GetDefaultFlags(type2));
SetWorkstation(GetDefaultWorkstation());
string domain = GetDefaultDomain();
SetDomain(domain);
string user = GetDefaultUser();
SetUser(user);
string password = GetDefaultPassword();
switch (LmCompatibility)
{
case 0:
case 1:
{
SetLmResponse(GetLMResponse(type2, password));
SetNtResponse(GetNTResponse(type2, password));
break;
}
case 2:
{
byte[] nt = GetNTResponse(type2, password);
SetLmResponse(nt);
SetNtResponse(nt);
break;
}
case 3:
case 4:
case 5:
{
byte[] clientChallenge = new byte[8];
//RANDOM.NextBytes(clientChallenge);
SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge));
break;
}
default:
{
SetLmResponse(GetLMResponse(type2, password));
SetNtResponse(GetNTResponse(type2, password));
break;
}
}
}
/// <summary>Creates a Type-3 message in response to the given Type-2 message.</summary>
/// <remarks>Creates a Type-3 message in response to the given Type-2 message.</remarks>
/// <param name="type2">The Type-2 message which this represents a response to.</param>
/// <param name="password">The password to use when constructing the response.</param>
/// <param name="domain">The domain in which the user has an account.</param>
/// <param name="user">The username for the authenticating user.</param>
/// <param name="workstation">
/// The workstation from which authentication is
/// taking place.
/// </param>
public Type3Message(Type2Message type2, string password, string domain, string user
, string workstation, int flags)
{
SetFlags(flags | GetDefaultFlags(type2));
if (workstation == null)
{
workstation = GetDefaultWorkstation();
}
SetWorkstation(workstation);
SetDomain(domain);
SetUser(user);
switch (LmCompatibility)
{
case 0:
case 1:
{
if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0)
{
SetLmResponse(GetLMResponse(type2, password));
SetNtResponse(GetNTResponse(type2, password));
}
else
{
// NTLM2 Session Response
byte[] clientChallenge = new byte[24];
//RANDOM.NextBytes(clientChallenge);
Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00)));
// NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient
byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password);
byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
type2.GetChallenge(), clientChallenge);
SetLmResponse(clientChallenge);
SetNtResponse(ntlm2Response);
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
{
byte[] sessionNonce = new byte[16];
Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8);
Array.Copy(clientChallenge, 0, sessionNonce, 8, 8);
Md4 md4 = new Md4();
md4.Update(responseKeyNt);
byte[] userSessionKey = md4.Digest();
Hmact64 hmac = new Hmact64(userSessionKey);
hmac.Update(sessionNonce);
byte[] ntlm2SessionKey = hmac.Digest();
if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
{
_masterKey = new byte[16];
//RANDOM.NextBytes(masterKey);
byte[] exchangedKey = new byte[16];
Rc4 rc4 = new Rc4(ntlm2SessionKey);
rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
SetSessionKey(exchangedKey);
}
else
{
_masterKey = ntlm2SessionKey;
SetSessionKey(_masterKey);
}
}
}
break;
}
case 2:
{
byte[] nt = GetNTResponse(type2, password);
SetLmResponse(nt);
SetNtResponse(nt);
break;
}
case 3:
case 4:
case 5:
{
byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password
);
byte[] clientChallenge1 = new byte[8];
//RANDOM.NextBytes(clientChallenge_1);
SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1));
byte[] clientChallenge2 = new byte[8];
//RANDOM.NextBytes(clientChallenge2);
SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2));
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
{
Hmact64 hmac = new Hmact64(responseKeyNt1);
hmac.Update(_ntResponse, 0, 16);
// only first 16 bytes of ntResponse
byte[] userSessionKey = hmac.Digest();
if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
{
_masterKey = new byte[16];
//RANDOM.NextBytes(masterKey);
byte[] exchangedKey = new byte[16];
Rc4 rc4 = new Rc4(userSessionKey);
rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
SetSessionKey(exchangedKey);
}
else
{
_masterKey = userSessionKey;
SetSessionKey(_masterKey);
}
}
break;
}
default:
{
SetLmResponse(GetLMResponse(type2, password));
SetNtResponse(GetNTResponse(type2, password));
break;
}
}
}
/// <summary>Creates a Type-3 message with the specified parameters.</summary>
/// <remarks>Creates a Type-3 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="lmResponse">The LanManager/LMv2 response.</param>
/// <param name="ntResponse">The NT/NTLMv2 response.</param>
/// <param name="domain">The domain in which the user has an account.</param>
/// <param name="user">The username for the authenticating user.</param>
/// <param name="workstation">
/// The workstation from which authentication is
/// taking place.
/// </param>
public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse, string domain
, string user, string workstation)
{
SetFlags(flags);
SetLmResponse(lmResponse);
SetNtResponse(ntResponse);
SetDomain(domain);
SetUser(user);
SetWorkstation(workstation);
}
/// <summary>Creates a Type-3 message using the given raw Type-3 material.</summary>
/// <remarks>Creates a Type-3 message using the given raw Type-3 material.</remarks>
/// <param name="material">The raw Type-3 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// </exception>
public Type3Message(byte[] material)
{
Parse(material);
}
/// <summary>Returns the LanManager/LMv2 response.</summary>
/// <remarks>Returns the LanManager/LMv2 response.</remarks>
/// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
public virtual byte[] GetLMResponse()
{
return _lmResponse;
}
/// <summary>Sets the LanManager/LMv2 response for this message.</summary>
/// <remarks>Sets the LanManager/LMv2 response for this message.</remarks>
/// <param name="lmResponse">The LanManager response.</param>
public virtual void SetLmResponse(byte[] lmResponse)
{
this._lmResponse = lmResponse;
}
/// <summary>Returns the NT/NTLMv2 response.</summary>
/// <remarks>Returns the NT/NTLMv2 response.</remarks>
/// <returns>A <code>byte[]</code> containing the NT/NTLMv2 response.</returns>
public virtual byte[] GetNTResponse()
{
return _ntResponse;
}
/// <summary>Sets the NT/NTLMv2 response for this message.</summary>
/// <remarks>Sets the NT/NTLMv2 response for this message.</remarks>
/// <param name="ntResponse">The NT/NTLMv2 response.</param>
public virtual void SetNtResponse(byte[] ntResponse)
{
this._ntResponse = ntResponse;
}
/// <summary>Returns the domain in which the user has an account.</summary>
/// <remarks>Returns the domain in which the user has an account.</remarks>
/// <returns>A <code>String</code> containing the domain for the user.</returns>
public virtual string GetDomain()
{
return _domain;
}
/// <summary>Sets the domain for this message.</summary>
/// <remarks>Sets the domain for this message.</remarks>
/// <param name="domain">The domain.</param>
public virtual void SetDomain(string domain)
{
this._domain = domain;
}
/// <summary>Returns the username for the authenticating user.</summary>
/// <remarks>Returns the username for the authenticating user.</remarks>
/// <returns>A <code>String</code> containing the user for this message.</returns>
public virtual string GetUser()
{
return _user;
}
/// <summary>Sets the user for this message.</summary>
/// <remarks>Sets the user for this message.</remarks>
/// <param name="user">The user.</param>
public virtual void SetUser(string user)
{
this._user = user;
}
/// <summary>Returns the workstation from which authentication is being performed.</summary>
/// <remarks>Returns the workstation from which authentication is being performed.</remarks>
/// <returns>A <code>String</code> containing the workstation.</returns>
public virtual string GetWorkstation()
{
return _workstation;
}
/// <summary>Sets the workstation for this message.</summary>
/// <remarks>Sets the workstation for this message.</remarks>
/// <param name="workstation">The workstation.</param>
public virtual void SetWorkstation(string workstation)
{
this._workstation = workstation;
}
/// <summary>
/// The real session key if the regular session key is actually
/// the encrypted version used for key exchange.
/// </summary>
/// <remarks>
/// The real session key if the regular session key is actually
/// the encrypted version used for key exchange.
/// </remarks>
/// <returns>A <code>byte[]</code> containing the session key.</returns>
public virtual byte[] GetMasterKey()
{
return _masterKey;
}
/// <summary>Returns the session key.</summary>
/// <remarks>Returns the session key.</remarks>
/// <returns>A <code>byte[]</code> containing the session key.</returns>
public virtual byte[] GetSessionKey()
{
return _sessionKey;
}
/// <summary>Sets the session key.</summary>
/// <remarks>Sets the session key.</remarks>
/// <param name="sessionKey">The session key.</param>
public virtual void SetSessionKey(byte[] sessionKey)
{
this._sessionKey = sessionKey;
}
public override byte[] ToByteArray()
{
try
{
int flags = GetFlags();
bool unicode = (flags & NtlmsspNegotiateUnicode) != 0;
string oem = unicode ? null : GetOemEncoding();
string domainName = GetDomain();
byte[] domain = null;
if (!string.IsNullOrEmpty(domainName))
{
domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) :
Runtime.GetBytesForString(domainName, oem);
}
int domainLength = (domain != null) ? domain.Length : 0;
string userName = GetUser();
byte[] user = null;
if (!string.IsNullOrEmpty(userName))
{
user = unicode ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString
(userName.ToUpper(), oem);
}
int userLength = (user != null) ? user.Length : 0;
string workstationName = GetWorkstation();
byte[] workstation = null;
if (!string.IsNullOrEmpty(workstationName))
{
workstation = unicode ? Runtime.GetBytesForString(workstationName, UniEncoding
) : Runtime.GetBytesForString(workstationName.ToUpper(), oem);
}
int workstationLength = (workstation != null) ? workstation.Length : 0;
byte[] lmResponse = GetLMResponse();
int lmLength = (lmResponse != null) ? lmResponse.Length : 0;
byte[] ntResponse = GetNTResponse();
int ntLength = (ntResponse != null) ? ntResponse.Length : 0;
byte[] sessionKey = GetSessionKey();
int keyLength = (sessionKey != null) ? sessionKey.Length : 0;
byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength
+ ntLength + keyLength];
Array.Copy(NtlmsspSignature, 0, type3, 0, 8);
WriteULong(type3, 8, 3);
int offset = 64;
WriteSecurityBuffer(type3, 12, offset, lmResponse);
offset += lmLength;
WriteSecurityBuffer(type3, 20, offset, ntResponse);
offset += ntLength;
WriteSecurityBuffer(type3, 28, offset, domain);
offset += domainLength;
WriteSecurityBuffer(type3, 36, offset, user);
offset += userLength;
WriteSecurityBuffer(type3, 44, offset, workstation);
offset += workstationLength;
WriteSecurityBuffer(type3, 52, offset, sessionKey);
WriteULong(type3, 60, flags);
return type3;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override string ToString()
{
string user = GetUser();
string domain = GetDomain();
string workstation = GetWorkstation();
byte[] lmResponse = GetLMResponse();
byte[] ntResponse = GetNTResponse();
byte[] sessionKey = GetSessionKey();
return "Type3Message[domain=" + domain + ",user=" + user + ",workstation=" + workstation
+ ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>"
) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>"
) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>"
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
}
/// <summary>
/// Returns the default flags for a generic Type-3 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-3 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>
/// Returns the default flags for a Type-3 message created in response
/// to the given Type-2 message in the current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a Type-3 message created in response
/// to the given Type-2 message in the current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags(Type2Message type2)
{
if (type2 == null)
{
return DefaultFlags;
}
int flags = NtlmsspNegotiateNtlm;
flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem;
return flags;
}
/// <summary>
/// Constructs the LanManager response to the given Type-2 message using
/// the supplied password.
/// </summary>
/// <remarks>
/// Constructs the LanManager response to the given Type-2 message using
/// the supplied password.
/// </remarks>
/// <param name="type2">The Type-2 message.</param>
/// <param name="password">The password.</param>
/// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
public static byte[] GetLMResponse(Type2Message type2, string password)
{
if (type2 == null || password == null)
{
return null;
}
return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge
());
}
public static byte[] GetLMv2Response(Type2Message type2, string domain, string user
, string password, byte[] clientChallenge)
{
if (type2 == null || domain == null || user == null || password == null || clientChallenge
== null)
{
return null;
}
return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge
(), clientChallenge);
}
public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt,
byte[] clientChallenge)
{
if (type2 == null || responseKeyNt == null || clientChallenge == null)
{
return null;
}
long nanos1601 = (Runtime.CurrentTimeMillis() + MillisecondsBetween1970And1601
) * 10000L;
return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge
(), clientChallenge, nanos1601, type2.GetTargetInformation());
}
/// <summary>
/// Constructs the NT response to the given Type-2 message using
/// the supplied password.
/// </summary>
/// <remarks>
/// Constructs the NT response to the given Type-2 message using
/// the supplied password.
/// </remarks>
/// <param name="type2">The Type-2 message.</param>
/// <param name="password">The password.</param>
/// <returns>A <code>byte[]</code> containing the NT response.</returns>
public static byte[] GetNTResponse(Type2Message type2, string password)
{
if (type2 == null || password == null)
{
return null;
}
return NtlmPasswordAuthentication.GetNtlmResponse(password, type2.GetChallenge());
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>The default domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
/// <summary>Returns the default user from the current environment.</summary>
/// <remarks>Returns the default user from the current environment.</remarks>
/// <returns>The default user.</returns>
public static string GetDefaultUser()
{
return DefaultUser;
}
/// <summary>Returns the default password from the current environment.</summary>
/// <remarks>Returns the default password from the current environment.</remarks>
/// <returns>The default password.</returns>
public static string GetDefaultPassword()
{
return DefaultPassword;
}
/// <summary>Returns the default workstation from the current environment.</summary>
/// <remarks>Returns the default workstation from the current environment.</remarks>
/// <returns>The default workstation.</returns>
public static string GetDefaultWorkstation()
{
return DefaultWorkstation;
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 3)
{
throw new IOException("Not a Type 3 message.");
}
byte[] lmResponse = ReadSecurityBuffer(material, 12);
int lmResponseOffset = ReadULong(material, 16);
byte[] ntResponse = ReadSecurityBuffer(material, 20);
int ntResponseOffset = ReadULong(material, 24);
byte[] domain = ReadSecurityBuffer(material, 28);
int domainOffset = ReadULong(material, 32);
byte[] user = ReadSecurityBuffer(material, 36);
int userOffset = ReadULong(material, 40);
byte[] workstation = ReadSecurityBuffer(material, 44);
int workstationOffset = ReadULong(material, 48);
int flags;
string charset;
byte[] _sessionKey = null;
if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset
== 52 || workstationOffset == 52)
{
flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem;
charset = GetOemEncoding();
}
else
{
_sessionKey = ReadSecurityBuffer(material, 52);
flags = ReadULong(material, 60);
charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding
();
}
SetSessionKey(_sessionKey);
SetFlags(flags);
SetLmResponse(lmResponse);
SetNtResponse(ntResponse);
SetDomain(Runtime.GetStringForBytes(domain, charset));
SetUser(Runtime.GetStringForBytes(user, charset));
SetWorkstation(Runtime.GetStringForBytes(workstation, charset));
}
}
}

View File

@ -0,0 +1,287 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.Text;
using SharpCifs.Util;
namespace SharpCifs.Smb
{
/// <summary>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories.
/// </summary>
/// <remarks>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories. The Windows OS
/// determines which users have the necessary permissions to access objects
/// based on these entries.
/// <p>
/// To fully understand the information exposed by this class a description
/// of the access check algorithm used by Windows is required. The following
/// is a basic description of the algorithm. For a more complete description
/// we recommend reading the section on Access Control in Keith Brown's
/// "The .NET Developer's Guide to Windows Security" (which is also
/// available online).
/// <p>
/// Direct ACEs are evaluated first in order. The SID of the user performing
/// the operation and the desired access bits are compared to the SID
/// and access mask of each ACE. If the SID matches, the allow/deny flags
/// and access mask are considered. If the ACE is a "deny"
/// ACE and <i>any</i> of the desired access bits match bits in the access
/// mask of the ACE, the whole access check fails. If the ACE is an "allow"
/// ACE and <i>all</i> of the bits in the desired access bits match bits in
/// the access mask of the ACE, the access check is successful. Otherwise,
/// more ACEs are evaluated until all desired access bits (combined)
/// are "allowed". If all of the desired access bits are not "allowed"
/// the then same process is repeated for inherited ACEs.
/// <p>
/// For example, if user <tt>WNET\alice</tt> tries to open a file
/// with desired access bits <tt>0x00000003</tt> (<tt>FILE_READ_DATA |
/// FILE_WRITE_DATA</tt>) and the target file has the following security
/// descriptor ACEs:
/// <pre>
/// Allow WNET\alice 0x001200A9 Direct
/// Allow Administrators 0x001F01FF Inherited
/// Allow SYSTEM 0x001F01FF Inherited
/// </pre>
/// the access check would fail because the direct ACE has an access mask
/// of <tt>0x001200A9</tt> which doesn't have the
/// <tt>FILE_WRITE_DATA</tt> bit on (bit <tt>0x00000002</tt>). Actually, this isn't quite correct. If
/// <tt>WNET\alice</tt> is in the local <tt>Administrators</tt> group the access check
/// will succeed because the inherited ACE allows local <tt>Administrators</tt>
/// both <tt>FILE_READ_DATA</tt> and <tt>FILE_WRITE_DATA</tt> access.
/// </remarks>
public class Ace
{
public const int FileReadData = unchecked(0x00000001);
public const int FileWriteData = unchecked(0x00000002);
public const int FileAppendData = unchecked(0x00000004);
public const int FileReadEa = unchecked(0x00000008);
public const int FileWriteEa = unchecked(0x00000010);
public const int FileExecute = unchecked(0x00000020);
public const int FileDelete = unchecked(0x00000040);
public const int FileReadAttributes = unchecked(0x00000080);
public const int FileWriteAttributes = unchecked(0x00000100);
public const int Delete = unchecked(0x00010000);
public const int ReadControl = unchecked(0x00020000);
public const int WriteDac = unchecked(0x00040000);
public const int WriteOwner = unchecked(0x00080000);
public const int Synchronize = unchecked(0x00100000);
public const int GenericAll = unchecked(0x10000000);
public const int GenericExecute = unchecked(0x20000000);
public const int GenericWrite = unchecked(0x40000000);
public const int GenericRead = unchecked((int)(0x80000000));
public const int FlagsObjectInherit = unchecked(0x01);
public const int FlagsContainerInherit = unchecked(0x02);
public const int FlagsNoPropagate = unchecked(0x04);
public const int FlagsInheritOnly = unchecked(0x08);
public const int FlagsInherited = unchecked(0x10);
internal bool Allow;
internal int Flags;
internal int Access;
internal Sid Sid;
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 16
// 17
// 18
// 19
// 20
// 28
// 29
// 30
// 31
/// <summary>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</summary>
/// <remarks>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</remarks>
public virtual bool IsAllow()
{
return Allow;
}
/// <summary>Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// </summary>
/// <remarks>
/// Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// <p>
/// Note: For reasons not fully understood, <tt>FLAGS_INHERITED</tt> may
/// not be set within all security descriptors even though the ACE was in
/// face inherited. If an inherited ACE is added to a parent the Windows
/// ACL editor will rebuild all children ACEs and set this flag accordingly.
/// </remarks>
public virtual bool IsInherited()
{
return (Flags & FlagsInherited) != 0;
}
/// <summary>Returns the flags for this ACE.</summary>
/// <remarks>
/// Returns the flags for this ACE. The </tt>isInherited()</tt>
/// method checks the <tt>FLAGS_INHERITED</tt> bit in these flags.
/// </remarks>
public virtual int GetFlags()
{
return Flags;
}
/// <summary>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'.
/// </summary>
/// <remarks>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'. For
/// files the text is always 'This object only'.
/// </remarks>
public virtual string GetApplyToText()
{
switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly
))
{
case unchecked(0x00):
{
return "This folder only";
}
case unchecked(0x03):
{
return "This folder, subfolders and files";
}
case unchecked(0x0B):
{
return "Subfolders and files only";
}
case unchecked(0x02):
{
return "This folder and subfolders";
}
case unchecked(0x0A):
{
return "Subfolders only";
}
case unchecked(0x01):
{
return "This folder and files";
}
case unchecked(0x09):
{
return "Files only";
}
}
return "Invalid";
}
/// <summary>Returns the access mask accociated with this ACE.</summary>
/// <remarks>
/// Returns the access mask accociated with this ACE. Use the
/// constants for <tt>FILE_READ_DATA</tt>, <tt>FILE_WRITE_DATA</tt>,
/// <tt>READ_CONTROL</tt>, <tt>GENERIC_ALL</tt>, etc with bitwise
/// operators to determine which bits of the mask are on or off.
/// </remarks>
public virtual int GetAccessMask()
{
return Access;
}
/// <summary>Return the SID associated with this ACE.</summary>
/// <remarks>Return the SID associated with this ACE.</remarks>
public virtual Sid GetSid()
{
return Sid;
}
internal virtual int Decode(byte[] buf, int bi)
{
Allow = buf[bi++] == unchecked(unchecked(0x00));
Flags = buf[bi++] & unchecked(0xFF);
int size = ServerMessageBlock.ReadInt2(buf, bi);
bi += 2;
Access = ServerMessageBlock.ReadInt4(buf, bi);
bi += 4;
Sid = new Sid(buf, bi);
return size;
}
internal virtual void AppendCol(StringBuilder sb, string str, int width)
{
sb.Append(str);
int count = width - str.Length;
for (int i = 0; i < count; i++)
{
sb.Append(' ');
}
}
/// <summary>Return a string represeting this ACE.</summary>
/// <remarks>
/// Return a string represeting this ACE.
/// <p>
/// Note: This function should probably be changed to return SDDL
/// fragments but currently it does not.
/// </remarks>
public override string ToString()
{
int count;
int i;
string str;
StringBuilder sb = new StringBuilder();
sb.Append(IsAllow() ? "Allow " : "Deny ");
AppendCol(sb, Sid.ToDisplayString(), 25);
sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
sb.Append(IsInherited() ? "Inherited " : "Direct ");
AppendCol(sb, GetApplyToText(), 34);
return sb.ToString();
}
}
}

View File

@ -0,0 +1,25 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal interface IAllocInfo
{
long GetCapacity();
long GetFree();
}
}

View File

@ -0,0 +1,221 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal abstract class AndXServerMessageBlock : ServerMessageBlock
{
private const int AndxCommandOffset = 1;
private const int AndxReservedOffset = 2;
private const int AndxOffsetOffset = 3;
private byte _andxCommand = unchecked(unchecked(0xFF));
private int _andxOffset;
internal ServerMessageBlock Andx;
public AndXServerMessageBlock()
{
}
internal AndXServerMessageBlock(ServerMessageBlock andx)
{
if (andx != null)
{
this.Andx = andx;
_andxCommand = andx.Command;
}
}
internal virtual int GetBatchLimit(byte command)
{
return 0;
}
internal override int Encode(byte[] dst, int dstIndex)
{
int start = HeaderStart = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteAndXWireFormat(dst, dstIndex);
Length = dstIndex - start;
if (Digest != null)
{
Digest.Sign(dst, HeaderStart, Length, this, Response);
}
return Length;
}
internal override int Decode(byte[] buffer, int bufferIndex)
{
int start = HeaderStart = bufferIndex;
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
bufferIndex += ReadAndXWireFormat(buffer, bufferIndex);
Length = bufferIndex - start;
return Length;
}
internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2);
WordCount += 4;
// for command, reserved, and offset
dstIndex += WordCount + 1;
WordCount /= 2;
dst[start] = unchecked((byte)(WordCount & unchecked(0xFF)));
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF)));
dstIndex += ByteCount;
if (Andx == null || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command
))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF));
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
// dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
// dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde));
dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde));
// andx not used; return
return dstIndex - start;
}
Andx.BatchLevel = BatchLevel + 1;
dst[start + AndxCommandOffset] = _andxCommand;
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
_andxOffset = dstIndex - HeaderStart;
WriteInt2(_andxOffset, dst, start + AndxOffsetOffset);
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
Andx.Uid = Uid;
dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex
);
}
else
{
// the andx smb is not of type andx so lets just write it here and
// were done.
int andxStart = dstIndex;
Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex);
dstIndex += Andx.WordCount + 1;
Andx.WordCount /= 2;
dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)));
Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2);
dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF)
));
dstIndex += Andx.ByteCount;
}
return dstIndex - start;
}
internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
WordCount = buffer[bufferIndex++];
if (WordCount != 0)
{
_andxCommand = buffer[bufferIndex];
_andxOffset = ReadInt2(buffer, bufferIndex + 2);
if (_andxOffset == 0)
{
_andxCommand = unchecked(unchecked(0xFF));
}
if (WordCount > 2)
{
ReadParameterWordsWireFormat(buffer, bufferIndex + 4);
if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended)
{
WordCount += 8;
}
}
bufferIndex = start + 1 + (WordCount * 2);
}
ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (ByteCount != 0)
{
int n;
n = ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += ByteCount;
}
if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF)))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
}
else
{
if (Andx == null)
{
_andxCommand = unchecked(unchecked(0xFF));
throw new RuntimeException("no andx command supplied with response");
}
bufferIndex = HeaderStart + _andxOffset;
Andx.HeaderStart = HeaderStart;
Andx.Command = _andxCommand;
Andx.ErrorCode = ErrorCode;
Andx.Flags = Flags;
Andx.Flags2 = Flags2;
Andx.Tid = Tid;
Andx.Pid = Pid;
Andx.Uid = Uid;
Andx.Mid = Mid;
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer
, bufferIndex);
}
else
{
buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))
);
if (Andx.WordCount != 0)
{
if (Andx.WordCount > 2)
{
bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex);
}
}
Andx.ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (Andx.ByteCount != 0)
{
Andx.ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += Andx.ByteCount;
}
}
Andx.Received = true;
}
return bufferIndex - start;
}
public override string ToString()
{
return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand
, 2) + ",andxOffset=" + _andxOffset;
}
}
}

View File

@ -0,0 +1,80 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public class BufferCache
{
private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16
);
internal static object[] Cache = new object[MaxBuffers];
private static int _freeBuffers;
public static byte[] GetBuffer()
{
lock (Cache)
{
byte[] buf;
if (_freeBuffers > 0)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] != null)
{
buf = (byte[])Cache[i];
Cache[i] = null;
_freeBuffers--;
return buf;
}
}
}
buf = new byte[SmbComTransaction.TransactionBufSize];
return buf;
}
}
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
rsp)
{
lock (Cache)
{
req.TxnBuf = GetBuffer();
rsp.TxnBuf = GetBuffer();
}
}
public static void ReleaseBuffer(byte[] buf)
{
lock (Cache)
{
if (_freeBuffers < MaxBuffers)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] == null)
{
Cache[i] = buf;
_freeBuffers++;
return;
}
}
}
}
}
}
}

View File

@ -0,0 +1,389 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
public class Dfs
{
internal class CacheEntry
{
internal long Expiration;
internal Hashtable Map;
internal CacheEntry(long ttl)
{
if (ttl == 0)
{
ttl = Ttl;
}
Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L;
Map = new Hashtable();
}
}
internal static LogStream Log = LogStream.GetInstance();
internal static readonly bool StrictView = Config.GetBoolean("jcifs.smb.client.dfs.strictView"
, false);
internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300
);
internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled"
, false);
internal static CacheEntry FalseEntry = new CacheEntry(0L);
internal CacheEntry Domains;
internal CacheEntry Referrals;
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth)
{
if (Disabled || auth.Domain == "?")
{
return null;
}
if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration)
{
Domains = null;
}
if (Domains != null)
{
return Domains.Map;
}
try
{
UniAddress addr = UniAddress.GetByName(auth.Domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
CacheEntry entry = new CacheEntry(Ttl * 10L);
DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0);
if (dr != null)
{
DfsReferral start = dr;
do
{
string domain = dr.Server.ToLower();
entry.Map.Put(domain, new Hashtable());
dr = dr.Next;
}
while (dr != start);
Domains = entry;
return Domains.Map;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth
)
{
Hashtable domains = GetTrustedDomains(auth);
if (domains == null)
{
return false;
}
domain = domain.ToLower();
return domains.Get(domain) != null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
UniAddress addr = UniAddress.GetByName(domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1);
if (dr != null)
{
DfsReferral start = dr;
IOException e = null;
do
{
try
{
addr = UniAddress.GetByName(dr.Server);
return SmbTransport.GetSmbTransport(addr, 0);
}
catch (IOException ioe)
{
e = ioe;
}
dr = dr.Next;
}
while (dr != start);
throw e;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string
root, string path, NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
string p = "\\" + domain + "\\" + root;
if (path != null)
{
p += path;
}
DfsReferral dr = trans.GetDfsReferrals(auth, p, 0);
if (dr != null)
{
return dr;
}
}
catch (IOException ioe)
{
if (Log.Level >= 4)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication
auth)
{
lock (this)
{
DfsReferral dr = null;
long now = Runtime.CurrentTimeMillis();
if (Disabled || root.Equals("IPC$"))
{
return null;
}
Hashtable domains = GetTrustedDomains(auth);
if (domains != null)
{
domain = domain.ToLower();
Hashtable roots = (Hashtable)domains.Get(domain);
if (roots != null)
{
SmbTransport trans = null;
root = root.ToLower();
CacheEntry links = (CacheEntry)roots.Get(root);
if (links != null && now > links.Expiration)
{
//Sharpen.Collections.Remove(roots, root);
roots.Remove(root);
links = null;
}
if (links == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
int len = 1 + domain.Length + 1 + root.Length;
links = new CacheEntry(0L);
DfsReferral tmp = dr;
do
{
if (path == null)
{
// TODO: fix this
//tmp.map = links.map;
tmp.Key = "\\";
}
tmp.PathConsumed -= len;
tmp = tmp.Next;
}
while (tmp != dr);
if (dr.Key != null)
{
links.Map.Put(dr.Key, dr);
}
roots.Put(root, links);
}
else
{
if (path == null)
{
roots.Put(root, FalseEntry);
}
}
}
else
{
if (links == FalseEntry)
{
links = null;
}
}
if (links != null)
{
string link = "\\";
dr = (DfsReferral)links.Map.Get(link);
if (dr != null && now > dr.Expiration)
{
//Sharpen.Collections.Remove(links.map, link);
links.Map.Remove(link);
dr = null;
}
if (dr == null)
{
if (trans == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
dr.PathConsumed -= 1 + domain.Length + 1 + root.Length;
dr.Link = link;
links.Map.Put(link, dr);
}
}
}
}
}
if (dr == null && path != null)
{
if (Referrals != null && now > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
string key = "\\" + domain + "\\" + root;
if (path.Equals("\\") == false)
{
key += path;
}
key = key.ToLower();
//ListIterator<object> iter = new ListIterator<object>(referrals.map.Keys.GetEnumerator(), 0);
foreach (var current in Referrals.Map.Keys)
{
string _key = (string)current;
int klen = _key.Length;
bool match = false;
if (klen == key.Length)
{
match = _key.Equals(key);
}
else
{
if (klen < key.Length)
{
match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\';
}
}
if (match)
{
dr = (DfsReferral)Referrals.Map.Get(_key);
}
}
}
return dr;
}
}
internal virtual void Insert(string path, DfsReferral dr)
{
lock (this)
{
int s1;
int s2;
string server;
string share;
string key;
if (Disabled)
{
return;
}
s1 = path.IndexOf('\\', 1);
s2 = path.IndexOf('\\', s1 + 1);
server = Runtime.Substring(path, 1, s1);
share = Runtime.Substring(path, s1 + 1, s2);
key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower();
int ki = key.Length;
while (ki > 1 && key[ki - 1] == '\\')
{
ki--;
}
if (ki < key.Length)
{
key = Runtime.Substring(key, 0, ki);
}
dr.PathConsumed -= 1 + server.Length + 1 + share.Length;
if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
Referrals.Map.Put(key, dr);
}
}
}
}

View File

@ -0,0 +1,67 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.Collections.Generic;
namespace SharpCifs.Smb
{
public class DfsReferral : SmbException
{
public int PathConsumed;
public long Ttl;
public string Server;
public string Share;
public string Link;
public string Path;
public bool ResolveHashes;
public long Expiration;
internal DfsReferral Next;
internal IDictionary<string, DfsReferral> Map;
internal string Key = null;
public DfsReferral()
{
// Server
// Share
// Path relative to tree from which this referral was thrown
Next = this;
}
internal virtual void Append(DfsReferral dr)
{
dr.Next = Next;
Next = dr;
}
public override string ToString()
{
return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share="
+ Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" +
Expiration + ",resolveHashes=" + ResolveHashes + "]";
}
}
}

View File

@ -0,0 +1,64 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public static class DosError
{
public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked(
(int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)(
0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a
)) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(
0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked(
(int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)(
0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2
)) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked(
0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked(
(int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)(
0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc
)) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked(
0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked(
(int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)(
0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035
)) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked(
0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked(
(int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)(
0xC0000071)) } };
public static string[] DosErrorMessages = { "The operation completed successfully."
, "Incorrect function.", "Incorrect function.", "The system cannot find the file specified."
, "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function."
, "Access is denied.", "The TID specified was invalid.", "The handle is invalid."
, "The network name cannot be found.", "Not enough storage is available to process this command."
, "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning."
, "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process."
, "The process cannot access the file because it is being used by another process."
, "The process cannot access the file because another process has locked a portion of the file."
, "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found."
, "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session."
, "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended."
, "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty."
, "Cannot create a file when that file already exists.", "All pipe instances are busy."
, "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available."
, "This user account has expired.", "The user is not allowed to log on from this workstation."
, "The user is not allowed to log on at this time.", "The password of this user has expired."
};
}
}

View File

@ -0,0 +1,37 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public class DosFileFilter : ISmbFileFilter
{
protected internal string Wildcard;
protected internal int Attributes;
public DosFileFilter(string wildcard, int attributes)
{
this.Wildcard = wildcard;
this.Attributes = attributes;
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual bool Accept(SmbFile file)
{
return (file.GetAttributes() & Attributes) != 0;
}
}
}

View File

@ -0,0 +1,33 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public interface IFileEntry
{
string GetName();
int GetType();
int GetAttributes();
long CreateTime();
long LastModified();
long Length();
}
}

View File

@ -0,0 +1,29 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal interface IInfo
{
int GetAttributes();
long GetCreateTime();
long GetLastWriteTime();
long GetSize();
}
}

View File

@ -0,0 +1,122 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NetServerEnum2 : SmbComTransaction
{
internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF));
internal const int SvTypeDomainEnum = unchecked((int)(0x80000000));
internal static readonly string[] Descr = { "WrLehDO\u0000B16BBDz\u0000"
, "WrLehDz\u0000B16BBDz\u0000" };
internal string Domain;
internal string LastName;
internal int ServerTypes;
internal NetServerEnum2(string domain, int serverTypes)
{
this.Domain = domain;
this.ServerTypes = serverTypes;
Command = SmbComTransaction;
SubCommand = NetServerEnum2;
// not really true be used by upper logic
Name = "\\PIPE\\LANMAN";
MaxParameterCount = 8;
MaxDataCount = 16384;
MaxSetupCount = unchecked(unchecked(0x00));
SetupCount = 0;
Timeout = 5000;
}
internal override void Reset(int key, string lastName)
{
base.Reset();
this.LastName = lastName;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
int which = SubCommand == NetServerEnum2 ? 0 : 1;
try
{
descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII");
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
WriteInt4(ServerTypes, dst, dstIndex);
dstIndex += 4;
dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false);
if (which == 1)
{
dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false);
}
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes="
+ (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]";
}
}
}

View File

@ -0,0 +1,157 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class NetServerEnum2Response : SmbComTransactionResponse
{
internal class ServerInfo1 : IFileEntry
{
internal string Name;
internal int VersionMajor;
internal int VersionMinor;
internal int Type;
internal string CommentOrMasterBrowser;
public virtual string GetName()
{
return Name;
}
public new virtual int GetType()
{
return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup :
SmbFile.TypeServer;
}
public virtual int GetAttributes()
{
return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
}
public virtual long CreateTime()
{
return 0L;
}
public virtual long LastModified()
{
return 0L;
}
public virtual long Length()
{
return 0L;
}
public override string ToString()
{
return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString
(Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
}
internal ServerInfo1(NetServerEnum2Response enclosing)
{
this._enclosing = enclosing;
}
private readonly NetServerEnum2Response _enclosing;
}
private int _converter;
private int _totalAvailableEntries;
internal string LastName;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
ServerInfo1 e = null;
Results = new ServerInfo1[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new ServerInfo1(this);
e.Name = ReadString(buffer, bufferIndex, 16, false);
bufferIndex += 16;
e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF);
e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF);
e.Type = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
LastName = NumEntries == 0 ? null : e.Name;
return bufferIndex - start;
}
public override string ToString()
{
return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ _totalAvailableEntries + ",lastName=" + LastName + "]";
}
}
}

View File

@ -0,0 +1,95 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NetShareEnum : SmbComTransaction
{
private static readonly string Descr = "WrLeh\u0000B13BWz\u0000";
public NetShareEnum()
{
Command = SmbComTransaction;
SubCommand = NetShareEnum;
// not really true be used by upper logic
Name ="\\PIPE\\LANMAN";
MaxParameterCount = 8;
// maxDataCount = 4096; why was this set?
MaxSetupCount = 0x00;
SetupCount = 0;
Timeout = 5000;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
try
{
//descr = Runtime.GetBytesForString(Descr, "ASCII");
descr = Runtime.GetBytesForString(Descr, "UTF-8");
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(NetShareEnum, dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NetShareEnum[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,94 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class NetShareEnumResponse : SmbComTransactionResponse
{
private int _converter;
private int _totalAvailableEntries;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
SmbShareInfo e;
UseUnicode = false;
Results = new SmbShareInfo[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new SmbShareInfo();
e.NetName = ReadString(buffer, bufferIndex, 13, false);
bufferIndex += 14;
e.Type = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.Remark = ReadString(buffer, off, 128, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
return bufferIndex - start;
}
public override string ToString()
{
return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ _totalAvailableEntries + "]";
}
}
}

View File

@ -0,0 +1,202 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public static class NtStatus
{
public const int NtStatusOk = unchecked(0x00000000);
public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001));
public const int NtStatusNotImplemented = unchecked((int)(0xC0000002));
public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003));
public const int NtStatusAccessViolation = unchecked((int)(0xC0000005));
public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008));
public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d));
public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e));
public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)
);
public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023));
public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033));
public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034));
public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035));
public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037));
public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039));
public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a));
public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b));
public const int NtStatusSharingViolation = unchecked((int)(0xC0000043));
public const int NtStatusDeletePending = unchecked((int)(0xC0000056));
public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e));
public const int NtStatusUserExists = unchecked((int)(0xC0000063));
public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064));
public const int NtStatusWrongPassword = unchecked((int)(0xC000006a));
public const int NtStatusLogonFailure = unchecked((int)(0xC000006d));
public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e));
public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f));
public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070));
public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071));
public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072));
public const int NtStatusNoneMapped = unchecked((int)(0xC0000073));
public const int NtStatusInvalidSid = unchecked((int)(0xC0000078));
public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab));
public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac));
public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad));
public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae));
public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0));
public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1));
public const int NtStatusPipeListening = unchecked((int)(0xC00000b3));
public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba));
public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd));
public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9));
public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca));
public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc));
public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0));
public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da));
public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df));
public const int NtStatusNotADirectory = unchecked((int)(0xC0000103));
public const int NtStatusCannotDelete = unchecked((int)(0xC0000121));
public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122));
public const int NtStatusPipeBroken = unchecked((int)(0xC000014b));
public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151));
public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b));
public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b));
public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199
));
public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
public const int NtStatusNotFound = unchecked((int)(0xC0000225));
public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234));
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
));
public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful
, NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation
, NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice
, NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied
, NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound
, NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid
, NtStatusObjectPathNotFound, NtStatusObjectPathSyntaxBad, NtStatusSharingViolation
, NtStatusDeletePending, NtStatusNoLogonServers, NtStatusUserExists, NtStatusNoSuchUser
, NtStatusWrongPassword, NtStatusLogonFailure, NtStatusAccountRestriction
, NtStatusInvalidLogonHours, NtStatusInvalidWorkstation, NtStatusPasswordExpired
, NtStatusAccountDisabled, NtStatusNoneMapped, NtStatusInvalidSid, NtStatusInstanceNotAvailable
, NtStatusPipeNotAvailable, NtStatusInvalidPipeState, NtStatusPipeBusy
, NtStatusPipeDisconnected, NtStatusPipeClosing, NtStatusPipeListening,
NtStatusFileIsADirectory, NtStatusDuplicateName, NtStatusNetworkNameDeleted
, NtStatusNetworkAccessDenied, NtStatusBadNetworkName, NtStatusRequestNotAccepted
, NtStatusCantAccessDomainInfo, NtStatusNoSuchDomain, NtStatusNotADirectory
, NtStatusCannotDelete, NtStatusInvalidComputerName, NtStatusPipeBroken
, NtStatusNoSuchAlias, NtStatusLogonTypeNotGranted, NtStatusNoTrustSamAccount
, NtStatusTrustedDomainFailure, NtStatusNologonWorkstationTrustAccount,
NtStatusPasswordMustChange, NtStatusNotFound, NtStatusAccountLockedOut
, NtStatusPathNotCovered, NtStatusIoReparseTagNotHandled };
public static string[] NtStatusMessages = { "The operation completed successfully."
, "A device attached to the system is not functioning.", "Incorrect function.",
"The parameter is incorrect.", "Invalid access to memory location.", "The handle is invalid."
, "The parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified."
, "More data is available.", "Access is denied.", "The data area passed to a system call is too small."
, "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified."
, "Cannot create a file when that file already exists.", "The handle is invalid."
, "The specified path is invalid.", "The system cannot find the path specified."
, "The specified path is invalid.", "The process cannot access the file because it is being used by another process."
, "Access is denied.", "There are currently no logon servers available to service the logon request."
, "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct."
, "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction."
, "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer."
, "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled."
, "No mapping between account names and security IDs was done.", "The security ID structure is invalid."
, "All pipe instances are busy.", "All pipe instances are busy.", "The pipe state is invalid."
, "All pipe instances are busy.", "No process is on the other end of the pipe.",
"The pipe is being closed.", "Waiting for a process to open the other end of the pipe."
, "Access is denied.", "A duplicate name exists on the network.", "The specified network name is no longer available."
, "Network access is denied.", "The network name cannot be found.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."
, "Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved."
, "The specified domain did not exist.", "The directory name is invalid.", "Access is denied."
, "The format of the specified computer name is invalid.", "The pipe has been ended."
, "The specified local group does not exist.", "Logon failure: the user has not been granted the requested logon type at this computer."
, "The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship."
, "The trust relationship between the primary domain and the trusted domain failed."
, "The account used is a Computer Account. Use your global user account or local user account to access this server."
, "The user must change his password before he logs on the first time.", "NT_STATUS_NOT_FOUND"
, "The referenced account is currently locked out and may not be logged on to.",
"The remote system is not reachable by the transport.", "NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED"
};
}
}

View File

@ -0,0 +1,88 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class NtTransQuerySecurityDesc : SmbComNtTransaction
{
internal int Fid;
internal int SecurityInformation;
internal NtTransQuerySecurityDesc(int fid, int securityInformation)
{
this.Fid = fid;
this.SecurityInformation = securityInformation;
Command = SmbComNtTransact;
Function = NtTransactQuerySecurityDesc;
SetupCount = 0;
TotalDataCount = 0;
MaxParameterCount = 4;
MaxDataCount = 32768;
MaxSetupCount = unchecked(unchecked(0x00));
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(Fid, dst, dstIndex);
dstIndex += 2;
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(SecurityInformation, dst, dstIndex);
dstIndex += 4;
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump
.ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation
, 8) + "]";
}
}
}

View File

@ -0,0 +1,78 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse
{
internal SecurityDescriptor SecurityDescriptor;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
Length = ReadInt4(buffer, bufferIndex);
return 4;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
if (ErrorCode != 0)
{
return 4;
}
try
{
SecurityDescriptor = new SecurityDescriptor();
bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len);
}
catch (IOException ioe)
{
throw new RuntimeException(ioe.Message);
}
return bufferIndex - start;
}
public override string ToString()
{
return "NtTransQuerySecurityResponse[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,93 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
/// <summary>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
/// </summary>
/// <remarks>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for complete details.
/// </remarks>
public abstract class NtlmAuthenticator
{
private static NtlmAuthenticator _auth;
private string _url;
private SmbAuthException _sae;
private void Reset()
{
_url = null;
_sae = null;
}
/// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
/// <remarks>Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
/// </remarks>
public static void SetDefault(NtlmAuthenticator a)
{
lock (typeof(NtlmAuthenticator))
{
if (_auth != null)
{
return;
}
_auth = a;
}
}
protected internal string GetRequestingUrl()
{
return _url;
}
protected internal SmbAuthException GetRequestingException()
{
return _sae;
}
/// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </summary>
/// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </remarks>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
url, SmbAuthException sae)
{
if (_auth == null)
{
return null;
}
lock (_auth)
{
_auth._url = url;
_auth._sae = sae;
return _auth.GetNtlmPasswordAuthentication();
}
}
/// <summary>An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
/// </summary>
/// <remarks>
/// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
/// If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>.
/// </remarks>
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication
()
{
return null;
}
}
}

View File

@ -0,0 +1,40 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
namespace SharpCifs.Smb
{
public sealed class NtlmChallenge
{
public byte[] Challenge;
public UniAddress Dc;
internal NtlmChallenge(byte[] challenge, UniAddress dc)
{
this.Challenge = challenge;
this.Dc = dc;
}
public override string ToString()
{
return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge
.Length * 2) + ",dc=" + Dc + "]";
}
}
}

View File

@ -0,0 +1,206 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Ntlmssp;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
/// <summary>For initiating NTLM authentication (including NTLMv2).</summary>
/// <remarks>For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication.
/// </remarks>
public class NtlmContext
{
internal NtlmPasswordAuthentication Auth;
internal int NtlmsspFlags;
internal string Workstation;
internal bool isEstablished;
internal byte[] ServerChallenge;
internal byte[] SigningKey;
internal string NetbiosName = null;
internal int State = 1;
internal LogStream Log;
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
{
this.Auth = auth;
NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspNegotiate128;
if (doSigning)
{
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateKeyExch;
}
Workstation = Type1Message.GetDefaultWorkstation();
Log = LogStream.GetInstance();
}
public override string ToString()
{
string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString
(NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished
+ ",state=" + State + ",serverChallenge=";
if (ServerChallenge == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2);
}
ret += ",signingKey=";
if (SigningKey == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2);
}
ret += "]";
return ret;
}
public virtual bool IsEstablished()
{
return isEstablished;
}
public virtual byte[] GetServerChallenge()
{
return ServerChallenge;
}
public virtual byte[] GetSigningKey()
{
return SigningKey;
}
public virtual string GetNetbiosName()
{
return NetbiosName;
}
private string GetNtlmsspListItem(byte[] type2Token, int id0)
{
int ri = 58;
for (; ; )
{
int id = Encdec.Dec_uint16le(type2Token, ri);
int len = Encdec.Dec_uint16le(type2Token, ri + 2);
ri += 4;
if (id == 0 || (ri + len) > type2Token.Length)
{
break;
}
if (id == id0)
{
try
{
return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding
);
}
catch (UnsupportedEncodingException)
{
break;
}
}
ri += len;
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual byte[] InitSecContext(byte[] token, int offset, int len)
{
switch (State)
{
case 1:
{
Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation);
token = msg1.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg1);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
State++;
break;
}
case 2:
{
try
{
Type2Message msg2 = new Type2Message(token);
if (Log.Level >= 4)
{
Log.WriteLine(msg2);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
ServerChallenge = msg2.GetChallenge();
NtlmsspFlags &= msg2.GetFlags();
// netbiosName = getNtlmsspListItem(token, 0x0001);
Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(),
Auth.GetUsername(), Workstation, NtlmsspFlags);
token = msg3.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg3);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0)
{
SigningKey = msg3.GetMasterKey();
}
isEstablished = true;
State++;
break;
}
catch (Exception e)
{
throw new SmbException(e.Message, e);
}
}
default:
{
throw new SmbException("Invalid state");
}
}
return token;
}
}
}

View File

@ -0,0 +1,807 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
/// <summary>This class stores and encrypts NTLM user credentials.</summary>
/// <remarks>
/// This class stores and encrypts NTLM user credentials. The default
/// credentials are retrieved from the <tt>jcifs.smb.client.domain</tt>,
/// <tt>jcifs.smb.client.username</tt>, and <tt>jcifs.smb.client.password</tt>
/// properties.
/// <p>
/// Read <a href="../../../authhandler.html">jCIFS Exceptions and
/// NtlmAuthenticator</a> for related information.
/// </remarks>
public sealed class NtlmPasswordAuthentication : Principal
{
private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility"
, 3);
private static readonly Random Random = new Random();
private static LogStream _log = LogStream.GetInstance();
private static readonly byte[] S8 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) };
// KGS!@#$%
private static void E(byte[] key, byte[] data, byte[] e)
{
byte[] key7 = new byte[7];
byte[] e8 = new byte[8];
for (int i = 0; i < key.Length / 7; i++)
{
Array.Copy(key, i * 7, key7, 0, 7);
DES des = new DES(key7);
des.Encrypt(data, e8);
Array.Copy(e8, 0, e, i * 8, 8);
}
}
internal static string DefaultDomain;
internal static string DefaultUsername;
internal static string DefaultPassword;
internal static readonly string Blank = string.Empty;
public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication
(string.Empty, string.Empty, string.Empty);
internal static void InitDefaults()
{
if (DefaultDomain != null)
{
return;
}
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", "?");
DefaultUsername = Config.GetProperty("jcifs.smb.client.username", "GUEST");
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
}
/// <summary>Generate the ANSI DES hash for the password associated with these credentials.
/// </summary>
/// <remarks>Generate the ANSI DES hash for the password associated with these credentials.
/// </remarks>
public static byte[] GetPreNtlmResponse(string password, byte[] challenge)
{
byte[] p14 = new byte[14];
byte[] p21 = new byte[21];
byte[] p24 = new byte[24];
byte[] passwordBytes;
try
{
passwordBytes = Runtime.GetBytesForString(password.ToUpper(), SmbConstants.OemEncoding);
}
catch (UnsupportedEncodingException uee)
{
throw new RuntimeException("Try setting jcifs.encoding=US-ASCII", uee);
}
int passwordLength = passwordBytes.Length;
// Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
if (passwordLength > 14)
{
passwordLength = 14;
}
Array.Copy(passwordBytes, 0, p14, 0, passwordLength);
E(p14, S8, p21);
E(p21, challenge, p24);
return p24;
}
/// <summary>Generate the Unicode MD4 hash for the password associated with these credentials.
/// </summary>
/// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials.
/// </remarks>
public static byte[] GetNtlmResponse(string password, byte[] challenge)
{
byte[] uni = null;
byte[] p21 = new byte[21];
byte[] p24 = new byte[24];
try
{
uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding);
}
catch (UnsupportedEncodingException uee)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(uee, _log);
}
}
Md4 md4 = new Md4();
md4.Update(uni);
try
{
md4.Digest(p21, 0, 16);
}
catch (Exception ex)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ex, _log);
}
}
E(p21, challenge, p24);
return p24;
}
/// <summary>Creates the LMv2 response for the supplied information.</summary>
/// <remarks>Creates the LMv2 response for the supplied information.</remarks>
/// <param name="domain">The domain in which the username exists.</param>
/// <param name="user">The username.</param>
/// <param name="password">The user's password.</param>
/// <param name="challenge">The server challenge.</param>
/// <param name="clientChallenge">The client challenge (nonce).</param>
public static byte[] GetLMv2Response(string domain, string user, string password,
byte[] challenge, byte[] clientChallenge)
{
try
{
byte[] hash = new byte[16];
byte[] response = new byte[24];
// The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding
));
hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding
));
hmac = new Hmact64(hmac.Digest());
hmac.Update(challenge);
hmac.Update(clientChallenge);
hmac.Digest(response, 0, 16);
Array.Copy(clientChallenge, 0, response, 16, 8);
return response;
}
catch (Exception ex)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ex, _log);
}
return null;
}
}
public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte
[] clientChallenge)
{
byte[] sessionHash = new byte[8];
try
{
MessageDigest md5;
md5 = MessageDigest.GetInstance("MD5");
md5.Update(serverChallenge);
md5.Update(clientChallenge, 0, 8);
Array.Copy(md5.Digest(), 0, sessionHash, 0, 8);
}
catch (Exception gse)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(gse, _log);
}
throw new RuntimeException("MD5", gse);
}
byte[] key = new byte[21];
Array.Copy(nTowFv1, 0, key, 0, 16);
byte[] ntResponse = new byte[24];
E(key, sessionHash, ntResponse);
return ntResponse;
}
public static byte[] NtowFv1(string password)
{
if (password == null)
{
throw new RuntimeException("Password parameter is required");
}
try
{
Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
return md4.Digest();
}
catch (UnsupportedEncodingException uee)
{
throw new RuntimeException(uee.Message);
}
}
public static byte[] NtowFv2(string domain, string username, string password)
{
try
{
Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding
));
hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
return hmac.Digest();
}
catch (UnsupportedEncodingException uee)
{
throw new RuntimeException(uee.Message);
}
}
internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge
, byte[] clientData, int offset, int length)
{
Hmact64 hmac = new Hmact64(responseKey);
hmac.Update(serverChallenge);
hmac.Update(clientData, offset, length);
byte[] mac = hmac.Digest();
byte[] ret = new byte[mac.Length + clientData.Length];
Array.Copy(mac, 0, ret, 0, mac.Length);
Array.Copy(clientData, 0, ret, mac.Length, clientData.Length);
return ret;
}
public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge
, byte[] clientChallenge)
{
return ComputeResponse(responseKeyLm, serverChallenge
, clientChallenge, 0, clientChallenge.Length);
}
public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge
, byte[] clientChallenge, long nanos1601, byte[] targetInfo)
{
int targetInfoLength = targetInfo != null ? targetInfo.Length : 0;
byte[] temp = new byte[28 + targetInfoLength + 4];
Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0);
// Header
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 4);
// Reserved
Encdec.Enc_uint64le(nanos1601, temp, 8);
Array.Copy(clientChallenge, 0, temp, 16, 8);
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 24);
// Unknown
if (targetInfo != null)
{
Array.Copy(targetInfo, 0, temp, 28, targetInfoLength);
}
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength);
// mystery bytes!
return ComputeResponse(responseKeyNt, serverChallenge
, temp, 0, temp.Length);
}
internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication
(string.Empty, string.Empty, string.Empty);
internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication
("?", "GUEST", string.Empty);
internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication
(null);
internal string Domain;
internal string Username;
internal string Password;
internal byte[] AnsiHash;
internal byte[] UnicodeHash;
internal bool HashesExternal;
internal byte[] ClientChallenge;
internal byte[] Challenge;
/// <summary>
/// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
/// component of an SMB URL like "<tt>domain;user:pass</tt>".
/// </summary>
/// <remarks>
/// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
/// component of an SMB URL like "<tt>domain;user:pass</tt>". This constructor
/// is used internally be jCIFS when parsing SMB URLs.
/// </remarks>
public NtlmPasswordAuthentication(string userInfo)
{
Domain = Username = Password = null;
if (userInfo != null)
{
try
{
userInfo = Unescape(userInfo);
}
catch (UnsupportedEncodingException)
{
}
int i;
int u;
int end;
char c;
end = userInfo.Length;
for (i = 0, u = 0; i < end; i++)
{
c = userInfo[i];
if (c == ';')
{
Domain = Runtime.Substring(userInfo, 0, i);
u = i + 1;
}
else
{
if (c == ':')
{
Password = Runtime.Substring(userInfo, i + 1);
break;
}
}
}
Username = Runtime.Substring(userInfo, u, i);
}
InitDefaults();
if (Domain == null)
{
Domain = DefaultDomain;
}
if (Username == null)
{
Username = DefaultUsername;
}
if (Password == null)
{
Password = DefaultPassword;
}
}
/// <summary>
/// Create an <tt>NtlmPasswordAuthentication</tt> object from a
/// domain, username, and password.
/// </summary>
/// <remarks>
/// Create an <tt>NtlmPasswordAuthentication</tt> object from a
/// domain, username, and password. Parameters that are <tt>null</tt>
/// will be substituted with <tt>jcifs.smb.client.domain</tt>,
/// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
/// property values.
/// </remarks>
public NtlmPasswordAuthentication(string domain, string username, string password
)
{
int ci;
if (username != null)
{
ci = username.IndexOf('@');
if (ci > 0)
{
domain = Runtime.Substring(username, ci + 1);
username = Runtime.Substring(username, 0, ci);
}
else
{
ci = username.IndexOf('\\');
if (ci > 0)
{
domain = Runtime.Substring(username, 0, ci);
username = Runtime.Substring(username, ci + 1);
}
}
}
this.Domain = domain;
this.Username = username;
this.Password = password;
InitDefaults();
if (domain == null)
{
this.Domain = DefaultDomain;
}
if (username == null)
{
this.Username = DefaultUsername;
}
if (password == null)
{
this.Password = DefaultPassword;
}
}
/// <summary>
/// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
/// hashes.
/// </summary>
/// <remarks>
/// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
/// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
/// class which is in turn used by NTLM HTTP authentication functionality.
/// </remarks>
public NtlmPasswordAuthentication(string domain, string username, byte[] challenge
, byte[] ansiHash, byte[] unicodeHash)
{
if (domain == null || username == null || ansiHash == null || unicodeHash == null)
{
throw new ArgumentException("External credentials cannot be null");
}
this.Domain = domain;
this.Username = username;
Password = null;
this.Challenge = challenge;
this.AnsiHash = ansiHash;
this.UnicodeHash = unicodeHash;
HashesExternal = true;
}
/// <summary>Returns the domain.</summary>
/// <remarks>Returns the domain.</remarks>
public string GetDomain()
{
return Domain;
}
/// <summary>Returns the username.</summary>
/// <remarks>Returns the username.</remarks>
public string GetUsername()
{
return Username;
}
/// <summary>
/// Returns the password in plain text or <tt>null</tt> if the raw password
/// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
/// object which will be the case when NTLM HTTP Authentication is
/// used.
/// </summary>
/// <remarks>
/// Returns the password in plain text or <tt>null</tt> if the raw password
/// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
/// object which will be the case when NTLM HTTP Authentication is
/// used. There is no way to retrieve a users password in plain text unless
/// it is supplied by the user at runtime.
/// </remarks>
public string GetPassword()
{
return Password;
}
/// <summary>
/// Return the domain and username in the format:
/// <tt>domain\\username</tt>.
/// </summary>
/// <remarks>
/// Return the domain and username in the format:
/// <tt>domain\\username</tt>. This is equivalent to <tt>toString()</tt>.
/// </remarks>
public new string GetName()
{
bool d = Domain.Length > 0 && Domain.Equals("?") == false;
return d ? Domain + "\\" + Username : Username;
}
/// <summary>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// </summary>
/// <remarks>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// </remarks>
public byte[] GetAnsiHash(byte[] challenge)
{
if (HashesExternal)
{
return AnsiHash;
}
switch (LmCompatibility)
{
case 0:
case 1:
{
return GetPreNtlmResponse(Password, challenge);
}
case 2:
{
return GetNtlmResponse(Password, challenge);
}
case 3:
case 4:
case 5:
{
if (ClientChallenge == null)
{
ClientChallenge = new byte[8];
Random.NextBytes(ClientChallenge);
}
return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge);
}
default:
{
return GetPreNtlmResponse(Password, challenge);
}
}
}
/// <summary>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// </summary>
/// <remarks>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// </remarks>
public byte[] GetUnicodeHash(byte[] challenge)
{
if (HashesExternal)
{
return UnicodeHash;
}
switch (LmCompatibility)
{
case 0:
case 1:
case 2:
{
return GetNtlmResponse(Password, challenge);
}
case 3:
case 4:
case 5:
{
return new byte[0];
}
default:
{
return GetNtlmResponse(Password, challenge);
}
}
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public byte[] GetSigningKey(byte[] challenge)
{
switch (LmCompatibility)
{
case 0:
case 1:
case 2:
{
byte[] signingKey = new byte[40];
GetUserSessionKey(challenge, signingKey, 0);
Array.Copy(GetUnicodeHash(challenge), 0, signingKey, 16, 24);
return signingKey;
}
case 3:
case 4:
case 5:
{
throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)"
);
}
}
return null;
}
/// <summary>Returns the effective user session key.</summary>
/// <remarks>Returns the effective user session key.</remarks>
/// <param name="challenge">The server challenge.</param>
/// <returns>
/// A <code>byte[]</code> containing the effective user session key,
/// used in SMB MAC signing and NTLMSSP signing and sealing.
/// </returns>
public byte[] GetUserSessionKey(byte[] challenge)
{
if (HashesExternal)
{
return null;
}
byte[] key = new byte[16];
try
{
GetUserSessionKey(challenge, key, 0);
}
catch (Exception ex)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ex, _log);
}
}
return key;
}
/// <summary>Calculates the effective user session key.</summary>
/// <remarks>Calculates the effective user session key.</remarks>
/// <param name="challenge">The server challenge.</param>
/// <param name="dest">
/// The destination array in which the user session key will be
/// placed.
/// </param>
/// <param name="offset">
/// The offset in the destination array at which the
/// session key will start.
/// </param>
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset)
{
if (HashesExternal)
{
return;
}
try
{
Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)
);
switch (LmCompatibility)
{
case 0:
case 1:
case 2:
{
md4.Update(md4.Digest());
md4.Digest(dest, offset, 16);
break;
}
case 3:
case 4:
case 5:
{
if (ClientChallenge == null)
{
ClientChallenge = new byte[8];
Random.NextBytes(ClientChallenge);
}
Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding
));
hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding
));
byte[] ntlmv2Hash = hmac.Digest();
hmac = new Hmact64(ntlmv2Hash);
hmac.Update(challenge);
hmac.Update(ClientChallenge);
Hmact64 userKey = new Hmact64(ntlmv2Hash);
userKey.Update(hmac.Digest());
userKey.Digest(dest, offset, 16);
break;
}
default:
{
md4.Update(md4.Digest());
md4.Digest(dest, offset, 16);
break;
}
}
}
catch (Exception e)
{
throw new SmbException(string.Empty, e);
}
}
/// <summary>
/// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
/// equality.
/// </summary>
/// <remarks>
/// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
/// equality. Two <tt>NtlmPasswordAuthentication</tt> objects are equal if
/// their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one <tt>NtlmPasswordAuthentication</tt> object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method.
/// </remarks>
public override bool Equals(object obj)
{
if (obj is NtlmPasswordAuthentication)
{
NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication
)obj;
if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals
(Username.ToUpper()))
{
if (HashesExternal && ntlm.HashesExternal)
{
return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm.
UnicodeHash);
}
if (!HashesExternal && Password.Equals(ntlm.Password))
{
return true;
}
}
}
return false;
}
/// <summary>Return the upcased username hash code.</summary>
/// <remarks>Return the upcased username hash code.</remarks>
public override int GetHashCode()
{
return GetName().ToUpper().GetHashCode();
}
/// <summary>
/// Return the domain and username in the format:
/// <tt>domain\\username</tt>.
/// </summary>
/// <remarks>
/// Return the domain and username in the format:
/// <tt>domain\\username</tt>. This is equivalent to <tt>getName()</tt>.
/// </remarks>
public override string ToString()
{
return GetName();
}
/// <exception cref="System.FormatException"></exception>
/// <exception cref="UnsupportedEncodingException"></exception>
internal static string Unescape(string str)
{
char ch;
int i;
int j;
int state;
int len;
char[] @out;
byte[] b = new byte[1];
if (str == null)
{
return null;
}
len = str.Length;
@out = new char[len];
state = 0;
for (i = j = 0; i < len; i++)
{
switch (state)
{
case 0:
{
ch = str[i];
if (ch == '%')
{
state = 1;
}
else
{
@out[j++] = ch;
}
break;
}
case 1:
{
b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i,
i + 2), 16) & unchecked(0xFF)));
@out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0];
i++;
state = 0;
break;
}
}
}
return new string(@out, 0, j);
}
}
}

View File

@ -0,0 +1,28 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public class Principal
{
private string _name = "";
public string GetName()
{
return _name;
}
}
}

View File

@ -0,0 +1,900 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SharpCifs.Dcerpc;
using SharpCifs.Dcerpc.Msrpc;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
using Hashtable = SharpCifs.Util.Sharpen.Hashtable; //not System.Collections.Hashtable
namespace SharpCifs.Smb
{
/// <summary>
/// A Windows SID is a numeric identifier used to represent Windows
/// accounts.
/// </summary>
/// <remarks>
/// A Windows SID is a numeric identifier used to represent Windows
/// accounts. SIDs are commonly represented using a textual format such as
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt> but they may
/// also be resolved to yield the name of the associated Windows account
/// such as <tt>Administrators</tt> or <tt>MYDOM\alice</tt>.
/// <p>
/// Consider the following output of <tt>examples/SidLookup.java</tt>:
/// <pre>
/// toString: S-1-5-21-4133388617-793952518-2001621813-512
/// toDisplayString: WNET\Domain Admins
/// getType: 2
/// getTypeText: Domain group
/// getDomainName: WNET
/// getAccountName: Domain Admins
/// </pre>
/// </remarks>
public class Sid : Rpc.SidT
{
public const int SidTypeUseNone = Lsarpc.SidNameUseNone;
public const int SidTypeUser = Lsarpc.SidNameUser;
public const int SidTypeDomGrp = Lsarpc.SidNameDomGrp;
public const int SidTypeDomain = Lsarpc.SidNameDomain;
public const int SidTypeAlias = Lsarpc.SidNameAlias;
public const int SidTypeWknGrp = Lsarpc.SidNameWknGrp;
public const int SidTypeDeleted = Lsarpc.SidNameDeleted;
public const int SidTypeInvalid = Lsarpc.SidNameInvalid;
public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
internal static readonly string[] SidTypeNames = { "0", "User", "Domain group"
, "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" };
public const int SidFlagResolveSids = unchecked(0x0001);
public static Sid Everyone;
public static Sid CreatorOwner;
public static Sid SYSTEM;
static Sid()
{
try
{
Everyone = new Sid("S-1-1-0");
CreatorOwner = new Sid("S-1-3-0");
SYSTEM = new Sid("S-1-5-18");
}
catch (SmbException)
{
}
}
internal static Hashtable SidCache = new Hashtable();
/// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle
, Sid[] sids)
{
MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
handle.Sendrecv(rpc);
switch (rpc.Retval)
{
case 0:
case NtStatus.NtStatusNoneMapped:
case unchecked(0x00000107):
{
// NT_STATUS_SOME_NOT_MAPPED
break;
}
default:
{
throw new SmbException(rpc.Retval, false);
}
}
for (int si = 0; si < sids.Length; si++)
{
sids[si].Type = rpc.Names.Names[si].SidType;
sids[si].DomainName = null;
switch (sids[si].Type)
{
case SidTypeUser:
case SidTypeDomGrp:
case SidTypeDomain:
case SidTypeAlias:
case SidTypeWknGrp:
{
int sidIndex = rpc.Names.Names[si].SidIndex;
Rpc.Unicode_string ustr = rpc.Domains.Domains[sidIndex].Name;
sids[si].DomainName = (new UnicodeString(ustr, false)).ToString();
break;
}
}
sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString
();
sids[si].OriginServer = null;
sids[si].OriginAuth = null;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids)
{
DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null;
lock (SidCache)
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]"
, auth);
string server = authorityServerName;
int dot = server.IndexOf('.');
if (dot > 0 && char.IsDigit(server[0]) == false)
{
server = Runtime.Substring(server, 0, dot);
}
policyHandle = new LsaPolicyHandle(handle, "\\\\" + server, unchecked(0x00000800));
ResolveSids(handle, policyHandle, sids);
}
finally
{
if (handle != null)
{
if (policyHandle != null)
{
policyHandle.Close();
}
handle.Close();
}
}
}
}
/// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids, int offset, int length)
{
List<object> list = new List<object>();//new List<object>(sids.Length);
int si;
lock (SidCache)
{
for (si = 0; si < length; si++)
{
Sid sid = (Sid)SidCache.Get(sids[offset + si]);
if (sid != null)
{
sids[offset + si].Type = sid.Type;
sids[offset + si].DomainName = sid.DomainName;
sids[offset + si].AcctName = sid.AcctName;
}
else
{
list.Add(sids[offset + si]);
}
}
if (list.Count > 0)
{
//sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
sids = (Sid[])list.ToArray();
ResolveSids0(authorityServerName, auth, sids);
for (si = 0; si < sids.Length; si++)
{
SidCache.Put(sids[si], sids[si]);
}
}
}
}
/// <summary>Resolve an array of SIDs using a cache and at most one MSRPC request.</summary>
/// <remarks>
/// Resolve an array of SIDs using a cache and at most one MSRPC request.
/// <p>
/// This method will attempt
/// to resolve SIDs using a cache and cache the results of any SIDs that
/// required resolving with the authority. SID cache entries are currently not
/// expired because under normal circumstances SID information never changes.
/// </remarks>
/// <param name="authorityServerName">The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority.
/// </param>
/// <param name="auth">The credentials that should be used to communicate with the named server. As usual, <tt>null</tt> indicates that default credentials should be used.
/// </param>
/// <param name="sids">The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the <tt>toDisplayString</tt>, <tt>getDomainName</tt>, and <tt>getAccountName</tt> methods.
/// </param>
/// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids)
{
List<object> list = new List<object>();//new List<object>(sids.Length);
int si;
lock (SidCache)
{
for (si = 0; si < sids.Length; si++)
{
Sid sid = (Sid)SidCache.Get(sids[si]);
if (sid != null)
{
sids[si].Type = sid.Type;
sids[si].DomainName = sid.DomainName;
sids[si].AcctName = sid.AcctName;
}
else
{
list.Add(sids[si]);
}
}
if (list.Count > 0)
{
//sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
sids = (Sid[]) list.ToArray();
ResolveSids0(authorityServerName, auth, sids);
for (si = 0; si < sids.Length; si++)
{
SidCache.Put(sids[si], sids[si]);
}
}
}
}
/// <exception cref="System.IO.IOException"></exception>
public static Sid GetServerSid(string server, NtlmPasswordAuthentication
auth)
{
DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null;
Lsarpc.LsarDomainInfo info = new Lsarpc.LsarDomainInfo();
MsrpcQueryInformationPolicy rpc;
lock (SidCache)
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth);
// NetApp doesn't like the 'generic' access mask values
policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001));
rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain
, info);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
return new Sid(info.Sid, SidTypeDomain, (new UnicodeString
(info.Name, false)).ToString(), null, false);
}
finally
{
if (handle != null)
{
if (policyHandle != null)
{
policyHandle.Close();
}
handle.Close();
}
}
}
}
public static byte[] ToByteArray(Rpc.SidT sid)
{
byte[] dst = new byte[1 + 1 + 6 + sid.SubAuthorityCount * 4];
int di = 0;
dst[di++] = sid.Revision;
dst[di++] = sid.SubAuthorityCount;
Array.Copy(sid.IdentifierAuthority, 0, dst, di, 6);
di += 6;
for (int ii = 0; ii < sid.SubAuthorityCount; ii++)
{
Encdec.Enc_uint32le(sid.SubAuthority[ii], dst, di);
di += 4;
}
return dst;
}
internal int Type;
internal string DomainName;
internal string AcctName;
internal string OriginServer;
internal NtlmPasswordAuthentication OriginAuth;
public Sid(byte[] src, int si)
{
Revision = src[si++];
SubAuthorityCount = src[si++];
IdentifierAuthority = new byte[6];
Array.Copy(src, si, IdentifierAuthority, 0, 6);
si += 6;
if (SubAuthorityCount > 100)
{
throw new RuntimeException("Invalid SID sub_authority_count");
}
SubAuthority = new int[SubAuthorityCount];
for (int i = 0; i < SubAuthorityCount; i++)
{
SubAuthority[i] = ServerMessageBlock.ReadInt4(src, si);
si += 4;
}
}
/// <summary>
/// Construct a SID from it's textual representation such as
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
/// </summary>
/// <remarks>
/// Construct a SID from it's textual representation such as
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
/// </remarks>
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public Sid(string textual)
{
StringTokenizer st = new StringTokenizer(textual, "-");
if (st.CountTokens() < 3 || !st.NextToken().Equals("S"))
{
// need S-N-M
throw new SmbException("Bad textual SID format: " + textual);
}
Revision = byte.Parse(st.NextToken());
string tmp = st.NextToken();
long id = 0;
if (tmp.StartsWith("0x"))
{
//id = long.Parse(Sharpen.Runtime.Substring(tmp, 2), 16);
id = long.Parse(Runtime.Substring(tmp, 2));
}
else
{
id = long.Parse(tmp);
}
IdentifierAuthority = new byte[6];
for (int i = 5; id > 0; i--)
{
IdentifierAuthority[i] = unchecked((byte)(id % 256));
id >>= 8;
}
SubAuthorityCount = unchecked((byte)st.CountTokens());
if (SubAuthorityCount > 0)
{
SubAuthority = new int[SubAuthorityCount];
for (int i1 = 0; i1 < SubAuthorityCount; i1++)
{
SubAuthority[i1] = (int)(long.Parse(st.NextToken()) & unchecked(0xFFFFFFFFL));
}
}
}
/// <summary>
/// Construct a SID from a domain SID and an RID
/// (relative identifier).
/// </summary>
/// <remarks>
/// Construct a SID from a domain SID and an RID
/// (relative identifier). For example, a domain SID
/// <tt>S-1-5-21-1496946806-2192648263-3843101252</tt> and RID <tt>1029</tt> would
/// yield the SID <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
/// </remarks>
public Sid(Sid domsid, int rid)
{
Revision = domsid.Revision;
IdentifierAuthority = domsid.IdentifierAuthority;
SubAuthorityCount = unchecked((byte)(domsid.SubAuthorityCount + 1));
SubAuthority = new int[SubAuthorityCount];
int i;
for (i = 0; i < domsid.SubAuthorityCount; i++)
{
SubAuthority[i] = domsid.SubAuthority[i];
}
SubAuthority[i] = rid;
}
public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority
)
{
Revision = sid.Revision;
SubAuthorityCount = sid.SubAuthorityCount;
IdentifierAuthority = sid.IdentifierAuthority;
SubAuthority = sid.SubAuthority;
this.Type = type;
this.DomainName = domainName;
this.AcctName = acctName;
if (decrementAuthority)
{
SubAuthorityCount--;
SubAuthority = new int[SubAuthorityCount];
for (int i = 0; i < SubAuthorityCount; i++)
{
SubAuthority[i] = sid.SubAuthority[i];
}
}
}
public virtual Sid GetDomainSid()
{
return new Sid(this, SidTypeDomain, DomainName, null, GetType()
!= SidTypeDomain);
}
public virtual int GetRid()
{
if (GetType() == SidTypeDomain)
{
throw new ArgumentException("This SID is a domain sid");
}
return SubAuthority[SubAuthorityCount - 1];
}
/// <summary>Returns the type of this SID indicating the state or type of account.</summary>
/// <remarks>
/// Returns the type of this SID indicating the state or type of account.
/// <p>
/// SID types are described in the following table.
/// <tt>
/// <table>
/// <tr><th>Type</th><th>Name</th></tr>
/// <tr><td>SID_TYPE_USE_NONE</td><td>0</td></tr>
/// <tr><td>SID_TYPE_USER</td><td>User</td></tr>
/// <tr><td>SID_TYPE_DOM_GRP</td><td>Domain group</td></tr>
/// <tr><td>SID_TYPE_DOMAIN</td><td>Domain</td></tr>
/// <tr><td>SID_TYPE_ALIAS</td><td>Local group</td></tr>
/// <tr><td>SID_TYPE_WKN_GRP</td><td>Builtin group</td></tr>
/// <tr><td>SID_TYPE_DELETED</td><td>Deleted</td></tr>
/// <tr><td>SID_TYPE_INVALID</td><td>Invalid</td></tr>
/// <tr><td>SID_TYPE_UNKNOWN</td><td>Unknown</td></tr>
/// </table>
/// </tt>
/// </remarks>
public virtual int GetType()
{
if (OriginServer != null)
{
ResolveWeak();
}
return Type;
}
/// <summary>
/// Return text represeting the SID type suitable for display to
/// users.
/// </summary>
/// <remarks>
/// Return text represeting the SID type suitable for display to
/// users. Text includes 'User', 'Domain group', 'Local group', etc.
/// </remarks>
public virtual string GetTypeText()
{
if (OriginServer != null)
{
ResolveWeak();
}
return SidTypeNames[Type];
}
/// <summary>
/// Return the domain name of this SID unless it could not be
/// resolved in which case the numeric representation is returned.
/// </summary>
/// <remarks>
/// Return the domain name of this SID unless it could not be
/// resolved in which case the numeric representation is returned.
/// </remarks>
public virtual string GetDomainName()
{
if (OriginServer != null)
{
ResolveWeak();
}
if (Type == SidTypeUnknown)
{
string full = ToString();
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length -
1);
}
return DomainName;
}
/// <summary>
/// Return the sAMAccountName of this SID unless it could not
/// be resolved in which case the numeric RID is returned.
/// </summary>
/// <remarks>
/// Return the sAMAccountName of this SID unless it could not
/// be resolved in which case the numeric RID is returned. If this
/// SID is a domain SID, this method will return an empty String.
/// </remarks>
public virtual string GetAccountName()
{
if (OriginServer != null)
{
ResolveWeak();
}
if (Type == SidTypeUnknown)
{
return string.Empty + SubAuthority[SubAuthorityCount - 1];
}
if (Type == SidTypeDomain)
{
return string.Empty;
}
return AcctName;
}
public override int GetHashCode()
{
int hcode = IdentifierAuthority[5];
for (int i = 0; i < SubAuthorityCount; i++)
{
hcode += 65599 * SubAuthority[i];
}
return hcode;
}
public override bool Equals(object obj)
{
if (obj is Sid)
{
Sid sid = (Sid)obj;
if (sid == this)
{
return true;
}
if (sid.SubAuthorityCount == SubAuthorityCount)
{
int i = SubAuthorityCount;
while (i-- > 0)
{
if (sid.SubAuthority[i] != SubAuthority[i])
{
return false;
}
}
for (i = 0; i < 6; i++)
{
if (sid.IdentifierAuthority[i] != IdentifierAuthority[i])
{
return false;
}
}
return sid.Revision == Revision;
}
}
return false;
}
/// <summary>
/// Return the numeric representation of this sid such as
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
/// </summary>
/// <remarks>
/// Return the numeric representation of this sid such as
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
/// </remarks>
public override string ToString()
{
string ret = "S-" + (Revision & unchecked(0xFF)) + "-";
if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked(
0))
{
ret += "0x";
ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
}
else
{
int shift = 0;
long id = 0;
for (int i = 5; i > 1; i--)
{
id += (IdentifierAuthority[i] & unchecked(0xFFL)) << shift;
shift += 8;
}
ret += id;
}
for (int i1 = 0; i1 < SubAuthorityCount; i1++)
{
ret += "-" + (SubAuthority[i1] & unchecked(0xFFFFFFFFL));
}
return ret;
}
/// <summary>
/// Return a String representing this SID ideal for display to
/// users.
/// </summary>
/// <remarks>
/// Return a String representing this SID ideal for display to
/// users. This method should return the same text that the ACL
/// editor in Windows would display.
/// <p>
/// Specifically, if the SID has
/// been resolved and it is not a domain SID or builtin account,
/// the full DOMAIN\name form of the account will be
/// returned (e.g. MYDOM\alice or MYDOM\Domain Users).
/// If the SID has been resolved but it is is a domain SID,
/// only the domain name will be returned (e.g. MYDOM).
/// If the SID has been resolved but it is a builtin account,
/// only the name component will be returned (e.g. SYSTEM).
/// If the sid cannot be resolved the numeric representation from
/// toString() is returned.
/// </remarks>
public virtual string ToDisplayString()
{
if (OriginServer != null)
{
ResolveWeak();
}
if (DomainName != null)
{
string str;
if (Type == SidTypeDomain)
{
str = DomainName;
}
else
{
if (Type == SidTypeWknGrp || DomainName.Equals("BUILTIN"))
{
if (Type == SidTypeUnknown)
{
str = ToString();
}
else
{
str = AcctName;
}
}
else
{
str = DomainName + "\\" + AcctName;
}
}
return str;
}
return ToString();
}
/// <summary>Manually resolve this SID.</summary>
/// <remarks>
/// Manually resolve this SID. Normally SIDs are automatically
/// resolved. However, if a SID is constructed explicitly using a SID
/// constructor, JCIFS will have no knowledge of the server that created the
/// SID and therefore cannot possibly resolve it automatically. In this case,
/// this method will be necessary.
/// </remarks>
/// <param name="authorityServerName">The FQDN of the server that is an authority for the SID.
/// </param>
/// <param name="auth">Credentials suitable for accessing the SID's information.</param>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication
auth)
{
Sid[] sids = new Sid[1];
sids[0] = this;
ResolveSids(authorityServerName, auth, sids);
}
internal virtual void ResolveWeak()
{
if (OriginServer != null)
{
try
{
Resolve(OriginServer, OriginAuth);
}
catch (IOException)
{
}
finally
{
OriginServer = null;
OriginAuth = null;
}
}
}
/// <exception cref="System.IO.IOException"></exception>
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle
domainHandle, Sid domsid, int rid, int flags)
{
SamrAliasHandle aliasHandle = null;
Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
MsrpcGetMembersInAlias rpc = null;
try
{
aliasHandle = new SamrAliasHandle(handle, domainHandle, unchecked(0x0002000c), rid);
rpc = new MsrpcGetMembersInAlias(aliasHandle, sidarray);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
Sid[] sids = new Sid[rpc.Sids.NumSids];
string originServer = handle.GetServer();
NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal
();
for (int i = 0; i < sids.Length; i++)
{
sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false);
sids[i].OriginServer = originServer;
sids[i].OriginAuth = originAuth;
}
if (sids.Length > 0 && (flags & SidFlagResolveSids) != 0)
{
ResolveSids(originServer, originAuth, sids);
}
return sids;
}
finally
{
if (aliasHandle != null)
{
aliasHandle.Close();
}
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication
auth, int flags)
{
if (Type != SidTypeDomGrp && Type != SidTypeAlias)
{
return new Sid[0];
}
DcerpcHandle handle = null;
SamrPolicyHandle policyHandle = null;
SamrDomainHandle domainHandle = null;
Sid domsid = GetDomainSid();
lock (SidCache)
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
, auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030));
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid);
return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(),
flags);
}
finally
{
if (handle != null)
{
if (policyHandle != null)
{
if (domainHandle != null)
{
domainHandle.Close();
}
policyHandle.Close();
}
handle.Close();
}
}
}
}
/// <summary>
/// This specialized method returns a Map of users and local groups for the
/// target server where keys are SIDs representing an account and each value
/// is an List<object> of SIDs represents the local groups that the account is
/// a member of.
/// </summary>
/// <remarks>
/// This specialized method returns a Map of users and local groups for the
/// target server where keys are SIDs representing an account and each value
/// is an List<object> of SIDs represents the local groups that the account is
/// a member of.
/// <p/>
/// This method is designed to assist with computing access control for a
/// given user when the target object's ACL has local groups. Local groups
/// are not listed in a user's group membership (e.g. as represented by the
/// tokenGroups constructed attribute retrived via LDAP).
/// <p/>
/// Domain groups nested inside a local group are currently not expanded. In
/// this case the key (SID) type will be SID_TYPE_DOM_GRP rather than
/// SID_TYPE_USER.
/// </remarks>
/// <param name="authorityServerName">The server from which the local groups will be queried.
/// </param>
/// <param name="auth">The credentials required to query groups and group members.</param>
/// <param name="flags">
/// Flags that control the behavior of the operation. When all
/// name associated with SIDs will be required, the SID_FLAG_RESOLVE_SIDS
/// flag should be used which causes all group member SIDs to be resolved
/// together in a single more efficient operation.
/// </param>
/// <exception cref="System.IO.IOException"></exception>
internal static Hashtable GetLocalGroupsMap(string authorityServerName, NtlmPasswordAuthentication
auth, int flags)
{
Sid domsid = GetServerSid(authorityServerName, auth);
DcerpcHandle handle = null;
SamrPolicyHandle policyHandle = null;
SamrDomainHandle domainHandle = null;
Samr.SamrSamArray sam = new Samr.SamrSamArray();
MsrpcEnumerateAliasesInDomain rpc;
lock (SidCache)
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
, auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000));
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid);
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam
);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
Hashtable map = new Hashtable();
for (int ei = 0; ei < rpc.Sam.Count; ei++)
{
Samr.SamrSamEntry entry = rpc.Sam.Entries[ei];
Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid
, entry.Idx, flags);
Sid groupSid = new Sid(domsid, entry.Idx);
groupSid.Type = SidTypeAlias;
groupSid.DomainName = domsid.GetDomainName();
groupSid.AcctName = (new UnicodeString(entry.Name, false)).ToString();
for (int mi = 0; mi < mems.Length; mi++)
{
List<object> groups = (List<object>)map.Get(mems[mi]);
if (groups == null)
{
groups = new List<object>();
map.Put(mems[mi], groups);
}
if (!groups.Contains(groupSid))
{
groups.Add(groupSid);
}
}
}
return map;
}
finally
{
if (handle != null)
{
if (policyHandle != null)
{
if (domainHandle != null)
{
domainHandle.Close();
}
policyHandle.Close();
}
handle.Close();
}
}
}
}
}
}

View File

@ -0,0 +1,101 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.IO;
namespace SharpCifs.Smb
{
public class SecurityDescriptor
{
public int Type;
public Ace[] Aces;
public SecurityDescriptor()
{
}
/// <exception cref="System.IO.IOException"></exception>
public SecurityDescriptor(byte[] buffer, int bufferIndex, int len)
{
Decode(buffer, bufferIndex, len);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual int Decode(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
bufferIndex++;
// revision
bufferIndex++;
Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to owner sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to group sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to sacl
bufferIndex += 4;
int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex = start + daclOffset;
bufferIndex++;
// revision
bufferIndex++;
int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
if (numAces > 4096)
{
throw new IOException("Invalid SecurityDescriptor");
}
if (daclOffset != 0)
{
Aces = new Ace[numAces];
for (int i = 0; i < numAces; i++)
{
Aces[i] = new Ace();
bufferIndex += Aces[i].Decode(buffer, bufferIndex);
}
}
else
{
Aces = null;
}
return bufferIndex - start;
}
public override string ToString()
{
string ret = "SecurityDescriptor:\n";
if (Aces != null)
{
for (int ai = 0; ai < Aces.Length; ai++)
{
ret += Aces[ai] + "\n";
}
}
else
{
ret += "NULL";
}
return ret;
}
}
}

View File

@ -0,0 +1,692 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
using SharpCifs.Util.Transport;
namespace SharpCifs.Smb
{
public abstract class ServerMessageBlock: Response
{
internal static LogStream Log = LogStream.GetInstance();
internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks;
internal static readonly byte[] Header = { 0xFF, (byte)('S'), (byte)('M'),
(byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
internal static void WriteInt2(long val, byte[] dst, int dstIndex)
{
dst[dstIndex] = unchecked((byte)(val));
dst[++dstIndex] = unchecked((byte)(val >> 8));
}
internal static void WriteInt4(long val, byte[] dst, int dstIndex)
{
dst[dstIndex] = unchecked((byte)(val));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >> 8));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8);
}
internal static int ReadInt4(byte[] src, int srcIndex)
{
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2]
& 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24);
}
internal static long ReadInt8(byte[] src, int srcIndex)
{
return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4
(src, srcIndex + 4)) << 32);
}
internal static void WriteInt8(long val, byte[] dst, int dstIndex)
{
dst[dstIndex] = unchecked((byte)(val));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >>= 8));
dst[++dstIndex] = unchecked((byte)(val >> 8));
}
internal static long ReadTime(byte[] src, int srcIndex)
{
int low = ReadInt4(src, srcIndex);
int hi = ReadInt4(src, srcIndex + 4);
long t = ((long)hi << (int)32L) | (low & unchecked((long)(0xFFFFFFFFL)));
t = (t / 10000L - SmbConstants.MillisecondsBetween1970And1601);
return t;
}
internal static void WriteTime(long t, byte[] dst, int dstIndex)
{
if (t != 0L)
{
t = (t + SmbConstants.MillisecondsBetween1970And1601) * 10000L;
}
WriteInt8(t, dst, dstIndex);
}
internal static long ReadUTime(byte[] buffer, int bufferIndex)
{
return ReadInt4(buffer, bufferIndex) * 1000L;
}
internal static void WriteUTime(long t, byte[] dst, int dstIndex)
{
if (t == 0L || t == unchecked((long)(0xFFFFFFFFFFFFFFFFL)))
{
WriteInt4(unchecked((int)(0xFFFFFFFF)), dst, dstIndex);
return;
}
// t isn't in DST either
WriteInt4((int)(t / 1000L), dst, dstIndex);
}
internal const byte SmbComCreateDirectory = 0x00;
internal const byte SmbComDeleteDirectory = 0x01;
internal const byte SmbComClose = 0x04;
internal const byte SmbComDelete = 0x06;
internal const byte SmbComRename = 0x07;
internal const byte SmbComQueryInformation = 0x08;
internal const byte SmbComWrite = 0x0B;
internal const byte SmbComCheckDirectory = 0x10;
internal const byte SmbComTransaction = 0x25;
internal const byte SmbComTransactionSecondary = 0x26;
internal const byte SmbComMove = 0x2A;
internal const byte SmbComEcho = 0x2B;
internal const byte SmbComOpenAndx = 0x2D;
internal const byte SmbComReadAndx = 0x2E;
internal const byte SmbComWriteAndx = 0x2F;
internal const byte SmbComTransaction2 = 0x32;
internal const byte SmbComFindClose2 = 0x34;
internal const byte SmbComTreeDisconnect = 0x71;
internal const byte SmbComNegotiate = 0x72;
internal const byte SmbComSessionSetupAndx = 0x73;
internal const byte SmbComLogoffAndx = 0x74;
internal const byte SmbComTreeConnectAndx = 0x75;
internal const byte SmbComNtTransact = 0xA0;
internal const byte SmbComNtTransactSecondary = 0xA1;
internal const byte SmbComNtCreateAndx = 0xA2;
internal byte Command;
internal byte Flags;
internal int HeaderStart;
internal int Length;
internal int BatchLevel;
internal int ErrorCode;
internal int Flags2;
internal int Tid;
internal int Pid;
internal int Uid;
internal int Mid;
internal int WordCount;
internal int ByteCount;
internal bool UseUnicode;
internal bool Received;
internal bool ExtendedSecurity;
internal long ResponseTimeout = 1;
internal int SignSeq;
internal bool VerifyFailed;
internal NtlmPasswordAuthentication Auth = null;
internal string Path;
internal SigningDigest Digest;
internal ServerMessageBlock Response;
public ServerMessageBlock()
{
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
));
Pid = SmbConstants.Pid;
BatchLevel = 0;
}
internal virtual void Reset()
{
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
));
Flags2 = 0;
ErrorCode = 0;
Received = false;
Digest = null;
}
internal virtual int WriteString(string str, byte[] dst, int dstIndex)
{
return WriteString(str, dst, dstIndex, UseUnicode);
}
internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode
)
{
int start = dstIndex;
try
{
if (useUnicode)
{
// Unicode requires word alignment
if (((dstIndex - HeaderStart) % 2) != 0)
{
dst[dstIndex++] = (byte)('\0');
}
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex
, str.Length * 2);
dstIndex += str.Length * 2;
dst[dstIndex++] = (byte)('\0');
dst[dstIndex++] = (byte)('\0');
}
else
{
byte[] b = Runtime.GetBytesForString(str, SmbConstants.OemEncoding);
Array.Copy(b, 0, dst, dstIndex, b.Length);
dstIndex += b.Length;
dst[dstIndex++] = (byte)('\0');
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
return dstIndex - start;
}
internal virtual string ReadString(byte[] src, int srcIndex)
{
return ReadString(src, srcIndex, 256, UseUnicode);
}
internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode
)
{
int len = 0;
string str = null;
try
{
if (useUnicode)
{
// Unicode requires word alignment
if (((srcIndex - HeaderStart) % 2) != 0)
{
srcIndex++;
}
while (src[srcIndex + len] != 0x00 || src[srcIndex
+ len + 1] != 0x00)
{
len += 2;
if (len > maxLen)
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
}
throw new RuntimeException("zero termination not found");
}
}
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
}
else
{
while (src[srcIndex + len] != 0x00)
{
len++;
if (len > maxLen)
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
}
throw new RuntimeException("zero termination not found");
}
}
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
return str;
}
internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen
, bool useUnicode)
{
int len = 0;
string str = null;
try
{
if (useUnicode)
{
// Unicode requires word alignment
if (((srcIndex - HeaderStart) % 2) != 0)
{
srcIndex++;
}
for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2)
{
if (src[srcIndex + len] == 0x00 && src[srcIndex
+ len + 1] == 0x00)
{
break;
}
if (len > maxLen)
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
}
throw new RuntimeException("zero termination not found");
}
}
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
}
else
{
for (len = 0; srcIndex < srcEnd; len++)
{
if (src[srcIndex + len] == 0x00)
{
break;
}
if (len > maxLen)
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
}
throw new RuntimeException("zero termination not found");
}
}
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
return str;
}
internal virtual int StringWireLength(string str, int offset)
{
int len = str.Length + 1;
if (UseUnicode)
{
len = str.Length * 2 + 2;
len = (offset % 2) != 0 ? len + 1 : len;
}
return len;
}
internal virtual int ReadStringLength(byte[] src, int srcIndex, int max)
{
int len = 0;
while (src[srcIndex + len] != 0x00)
{
if (len++ > max)
{
throw new RuntimeException("zero termination not found: " + this);
}
}
return len;
}
internal virtual int Encode(byte[] dst, int dstIndex)
{
int start = HeaderStart = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
WordCount = WriteParameterWordsWireFormat(dst, dstIndex + 1);
dst[dstIndex++] = unchecked((byte)((WordCount / 2) & 0xFF));
dstIndex += WordCount;
WordCount /= 2;
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
dst[dstIndex++] = unchecked((byte)(ByteCount & 0xFF));
dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & 0xFF));
dstIndex += ByteCount;
Length = dstIndex - start;
if (Digest != null)
{
Digest.Sign(dst, HeaderStart, Length, this, Response);
}
return Length;
}
internal virtual int Decode(byte[] buffer, int bufferIndex)
{
int start = HeaderStart = bufferIndex;
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
WordCount = buffer[bufferIndex++];
if (WordCount != 0)
{
int n;
if ((n = ReadParameterWordsWireFormat(buffer, bufferIndex)) != WordCount * 2)
{
if (Log.Level >= 5)
{
Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned "
+ n);
}
}
bufferIndex += WordCount * 2;
}
ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (ByteCount != 0)
{
int n;
if ((n = ReadBytesWireFormat(buffer, bufferIndex)) != ByteCount)
{
if (Log.Level >= 5)
{
Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n
);
}
}
// Don't think we can rely on n being correct here. Must use byteCount.
// Last paragraph of section 3.13.3 eludes to this.
bufferIndex += ByteCount;
}
Length = bufferIndex - start;
return Length;
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
Array.Copy(Header, 0, dst, dstIndex, Header.Length);
dst[dstIndex + SmbConstants.CmdOffset] = Command;
dst[dstIndex + SmbConstants.FlagsOffset] = Flags;
WriteInt2(Flags2, dst, dstIndex + SmbConstants.FlagsOffset + 1);
dstIndex += SmbConstants.TidOffset;
WriteInt2(Tid, dst, dstIndex);
WriteInt2(Pid, dst, dstIndex + 2);
WriteInt2(Uid, dst, dstIndex + 4);
WriteInt2(Mid, dst, dstIndex + 6);
return SmbConstants.HeaderLength;
}
internal virtual int ReadHeaderWireFormat(byte[] buffer, int bufferIndex)
{
Command = buffer[bufferIndex + SmbConstants.CmdOffset];
ErrorCode = ReadInt4(buffer, bufferIndex + SmbConstants.ErrorCodeOffset);
Flags = buffer[bufferIndex + SmbConstants.FlagsOffset];
Flags2 = ReadInt2(buffer, bufferIndex + SmbConstants.FlagsOffset + 1);
Tid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset);
Pid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 2);
Uid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 4);
Mid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 6);
return SmbConstants.HeaderLength;
}
internal virtual bool IsResponse()
{
return (Flags & SmbConstants.FlagsResponse) == SmbConstants.FlagsResponse;
}
internal abstract int WriteParameterWordsWireFormat(byte[] dst, int dstIndex);
internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
);
internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex);
public override int GetHashCode()
{
return Mid;
}
public override bool Equals(object obj)
{
return obj is ServerMessageBlock && ((ServerMessageBlock)obj)
.Mid == Mid;
}
public override string ToString()
{
string c;
switch (Command)
{
case SmbComNegotiate:
{
c = "SMB_COM_NEGOTIATE";
break;
}
case SmbComSessionSetupAndx:
{
c = "SMB_COM_SESSION_SETUP_ANDX";
break;
}
case SmbComTreeConnectAndx:
{
c = "SMB_COM_TREE_CONNECT_ANDX";
break;
}
case SmbComQueryInformation:
{
c = "SMB_COM_QUERY_INFORMATION";
break;
}
case SmbComCheckDirectory:
{
c = "SMB_COM_CHECK_DIRECTORY";
break;
}
case SmbComTransaction:
{
c = "SMB_COM_TRANSACTION";
break;
}
case SmbComTransaction2:
{
c = "SMB_COM_TRANSACTION2";
break;
}
case SmbComTransactionSecondary:
{
c = "SMB_COM_TRANSACTION_SECONDARY";
break;
}
case SmbComFindClose2:
{
c = "SMB_COM_FIND_CLOSE2";
break;
}
case SmbComTreeDisconnect:
{
c = "SMB_COM_TREE_DISCONNECT";
break;
}
case SmbComLogoffAndx:
{
c = "SMB_COM_LOGOFF_ANDX";
break;
}
case SmbComEcho:
{
c = "SMB_COM_ECHO";
break;
}
case SmbComMove:
{
c = "SMB_COM_MOVE";
break;
}
case SmbComRename:
{
c = "SMB_COM_RENAME";
break;
}
case SmbComDelete:
{
c = "SMB_COM_DELETE";
break;
}
case SmbComDeleteDirectory:
{
c = "SMB_COM_DELETE_DIRECTORY";
break;
}
case SmbComNtCreateAndx:
{
c = "SMB_COM_NT_CREATE_ANDX";
break;
}
case SmbComOpenAndx:
{
c = "SMB_COM_OPEN_ANDX";
break;
}
case SmbComReadAndx:
{
c = "SMB_COM_READ_ANDX";
break;
}
case SmbComClose:
{
c = "SMB_COM_CLOSE";
break;
}
case SmbComWriteAndx:
{
c = "SMB_COM_WRITE_ANDX";
break;
}
case SmbComCreateDirectory:
{
c = "SMB_COM_CREATE_DIRECTORY";
break;
}
case SmbComNtTransact:
{
c = "SMB_COM_NT_TRANSACT";
break;
}
case SmbComNtTransactSecondary:
{
c = "SMB_COM_NT_TRANSACT_SECONDARY";
break;
}
default:
{
c = "UNKNOWN";
break;
}
}
string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode);
return "command=" + c + ",received=" + Received + ",errorCode=" + str
+ ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x"
+ Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid="
+ Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount="
+ ByteCount;
}
}
}

View File

@ -0,0 +1,257 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
/// <summary>To filter 0 len updates and for debugging</summary>
public class SigningDigest
{
internal static LogStream Log = LogStream.GetInstance();
private MessageDigest _digest;
private byte[] _macSigningKey;
private bool _bypass;
private int _updates;
private int _signSequence;
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(byte[] macSigningKey, bool bypass)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
this._macSigningKey = macSigningKey;
this._bypass = bypass;
_updates = 0;
_signSequence = 0;
if (Log.Level >= 5)
{
Log.WriteLine("macSigningKey:");
Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length);
}
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
try
{
switch (SmbConstants.LmCompatibility)
{
case 0:
case 1:
case 2:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
, 16, 24);
break;
}
case 3:
case 4:
case 5:
{
_macSigningKey = new byte[16];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
break;
}
default:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
, 16, 24);
break;
}
}
}
catch (Exception ex)
{
throw new SmbException(string.Empty, ex);
}
if (Log.Level >= 5)
{
Log.WriteLine("LM_COMPATIBILITY=" + SmbConstants.LmCompatibility);
Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length);
}
}
public virtual void Update(byte[] input, int offset, int len)
{
if (Log.Level >= 5)
{
Log.WriteLine("update: " + _updates + " " + offset + ":" + len);
Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256));
Log.Flush();
}
if (len == 0)
{
return;
}
_digest.Update(input, offset, len);
_updates++;
}
public virtual byte[] Digest()
{
byte[] b;
b = _digest.Digest();
if (Log.Level >= 5)
{
Log.WriteLine("digest: ");
Hexdump.ToHexdump(Log, b, 0, b.Length);
Log.Flush();
}
_updates = 0;
return b;
}
/// <summary>Performs MAC signing of the SMB.</summary>
/// <remarks>
/// Performs MAC signing of the SMB. This is done as follows.
/// The signature field of the SMB is overwritted with the sequence number;
/// The MD5 digest of the MAC signing key + the entire SMB is taken;
/// The first 8 bytes of this are placed in the signature field.
/// </remarks>
/// <param name="data">The data.</param>
/// <param name="offset">The starting offset at which the SMB header begins.</param>
/// <param name="length">The length of the SMB data starting at offset.</param>
internal virtual void Sign(byte[] data, int offset, int length, ServerMessageBlock
request, ServerMessageBlock response)
{
request.SignSeq = _signSequence;
if (response != null)
{
response.SignSeq = _signSequence + 1;
response.VerifyFailed = false;
}
try
{
Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset + SmbConstants.SignatureOffset;
for (int i = 0; i < 8; i++)
{
data[index + i] = 0;
}
ServerMessageBlock.WriteInt4(_signSequence, data, index);
Update(data, offset, length);
Array.Copy(Digest(), 0, data, index, 8);
if (_bypass)
{
_bypass = false;
Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index,
8);
}
}
catch (Exception ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
}
finally
{
_signSequence += 2;
}
}
/// <summary>Performs MAC signature verification.</summary>
/// <remarks>
/// Performs MAC signature verification. This calculates the signature
/// of the SMB and compares it to the signature field on the SMB itself.
/// </remarks>
/// <param name="data">The data.</param>
/// <param name="offset">The starting offset at which the SMB header begins.</param>
/// <param name="length">The length of the SMB data starting at offset.</param>
internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response
)
{
Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset;
Update(data, index, SmbConstants.SignatureOffset);
index += SmbConstants.SignatureOffset;
byte[] sequence = new byte[8];
ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0);
Update(sequence, 0, sequence.Length);
index += 8;
if (response.Command == ServerMessageBlock.SmbComReadAndx)
{
SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
int length = response.Length - raxr.DataLength;
Update(data, index, length - SmbConstants.SignatureOffset - 8);
Update(raxr.B, raxr.Off, raxr.DataLength);
}
else
{
Update(data, index, response.Length - SmbConstants.SignatureOffset - 8);
}
byte[] signature = Digest();
for (int i = 0; i < 8; i++)
{
if (signature[i] != data[offset + SmbConstants.SignatureOffset + i])
{
if (Log.Level >= 2)
{
Log.WriteLine("signature verification failure");
Hexdump.ToHexdump(Log, signature, 0, 8);
Hexdump.ToHexdump(Log, data, offset + SmbConstants.SignatureOffset, 8);
}
return response.VerifyFailed = true;
}
}
return response.VerifyFailed = false;
}
public override string ToString()
{
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString
(_macSigningKey, 0, _macSigningKey.Length);
}
}
}

View File

@ -0,0 +1,36 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
/// <summary>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// </summary>
/// <remarks>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// <p>
/// See <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for more information about <code>SmbAuthException</code>.
/// </remarks>
public class SmbAuthException : SmbException
{
internal SmbAuthException(int errcode) : base(errcode, null)
{
}
}
}

View File

@ -0,0 +1,47 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComBlankResponse : ServerMessageBlock
{
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComBlankResponse[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,62 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComClose : ServerMessageBlock
{
private int _fid;
private long _lastWriteTime;
internal SmbComClose(int fid, long lastWriteTime)
{
this._fid = fid;
this._lastWriteTime = lastWriteTime;
Command = SmbComClose;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_fid, dst, dstIndex);
dstIndex += 2;
WriteUTime(_lastWriteTime, dst, dstIndex);
return 6;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComClose[" + base.ToString() + ",fid=" + _fid + ",lastWriteTime="
+ _lastWriteTime + "]";
}
}
}

View File

@ -0,0 +1,57 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComCreateDirectory : ServerMessageBlock
{
internal SmbComCreateDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComCreateDirectory;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComCreateDirectory[" + base.ToString() + ",directoryName="
+ Path + "]";
}
}
}

View File

@ -0,0 +1,63 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class SmbComDelete : ServerMessageBlock
{
private int _searchAttributes;
internal SmbComDelete(string fileName)
{
Path = fileName;
Command = SmbComDelete;
_searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_searchAttributes, dst, dstIndex);
return 2;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComDelete[" + base.ToString() + ",searchAttributes=0x" + Hexdump
.ToHexString(_searchAttributes, 4) + ",fileName=" + Path + "]";
}
}
}

View File

@ -0,0 +1,57 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComDeleteDirectory : ServerMessageBlock
{
internal SmbComDeleteDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComDeleteDirectory;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName="
+ Path + "]";
}
}
}

View File

@ -0,0 +1,56 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComFindClose2 : ServerMessageBlock
{
private int _sid;
internal SmbComFindClose2(int sid)
{
this._sid = sid;
Command = SmbComFindClose2;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_sid, dst, dstIndex);
return 2;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]";
}
}
}

View File

@ -0,0 +1,52 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComLogoffAndX : AndXServerMessageBlock
{
internal SmbComLogoffAndX(ServerMessageBlock andx) : base(andx)
{
Command = SmbComLogoffAndx;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComLogoffAndX[" + base.ToString() + "]";
}
}
}

View File

@ -0,0 +1,193 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class SmbComNtCreateAndX : AndXServerMessageBlock
{
internal const int FileSupersede = unchecked(0x0);
internal const int FileOpen = unchecked(0x1);
internal const int FileCreate = unchecked(0x2);
internal const int FileOpenIf = unchecked(0x3);
internal const int FileOverwrite = unchecked(0x4);
internal const int FileOverwriteIf = unchecked(0x5);
internal const int FileWriteThrough = unchecked(0x00000002);
internal const int FileSequentialOnly = unchecked(0x00000004);
internal const int FileSynchronousIoAlert = unchecked(0x00000010);
internal const int FileSynchronousIoNonalert = unchecked(0x00000020);
internal const int SecurityContextTracking = unchecked(0x01);
internal const int SecurityEffectiveOnly = unchecked(0x02);
private int _rootDirectoryFid;
private int _extFileAttributes;
private int _shareAccess;
private int _createDisposition;
private int _createOptions;
private int _impersonationLevel;
private long _allocationSize;
private byte _securityFlags;
private int _namelenIndex;
internal int Flags0;
internal int DesiredAccess;
internal SmbComNtCreateAndX(string name, int flags, int access, int shareAccess,
int extFileAttributes, int createOptions, ServerMessageBlock andx) : base(andx)
{
// share access specified in SmbFile
// create disposition
// create options
// security flags
Path = name;
Command = SmbComNtCreateAndx;
DesiredAccess = access;
DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes;
// extFileAttributes
this._extFileAttributes = extFileAttributes;
// shareAccess
this._shareAccess = shareAccess;
// createDisposition
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
{
// truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
_createDisposition = FileOverwriteIf;
}
else
{
_createDisposition = FileOverwrite;
}
}
else
{
// don't truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
{
// fail if already exists
_createDisposition = FileCreate;
}
else
{
_createDisposition = FileOpenIf;
}
}
else
{
_createDisposition = FileOpen;
}
}
if ((createOptions & unchecked(0x0001)) == 0)
{
this._createOptions = createOptions | unchecked(0x0040);
}
else
{
this._createOptions = createOptions;
}
_impersonationLevel = unchecked(0x02);
// As seen on NT :~)
_securityFlags = unchecked(unchecked(0x03));
}
// SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x00));
// name length without counting null termination
_namelenIndex = dstIndex;
dstIndex += 2;
WriteInt4(Flags0, dst, dstIndex);
dstIndex += 4;
WriteInt4(_rootDirectoryFid, dst, dstIndex);
dstIndex += 4;
WriteInt4(DesiredAccess, dst, dstIndex);
dstIndex += 4;
WriteInt8(_allocationSize, dst, dstIndex);
dstIndex += 8;
WriteInt4(_extFileAttributes, dst, dstIndex);
dstIndex += 4;
WriteInt4(_shareAccess, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createDisposition, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createOptions, dst, dstIndex);
dstIndex += 4;
WriteInt4(_impersonationLevel, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = _securityFlags;
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int n;
n = WriteString(Path, dst, dstIndex);
WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex);
return n;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComNTCreateAndX[" + base.ToString() + ",flags=0x" + Hexdump
.ToHexString(Flags0, 2) + ",rootDirectoryFid=" + _rootDirectoryFid + ",desiredAccess=0x"
+ Hexdump.ToHexString(DesiredAccess, 4) + ",allocationSize=" + _allocationSize +
",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) + ",shareAccess=0x"
+ Hexdump.ToHexString(_shareAccess, 4) + ",createDisposition=0x" + Hexdump.ToHexString
(_createDisposition, 4) + ",createOptions=0x" + Hexdump.ToHexString(_createOptions
, 8) + ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4) + ",securityFlags=0x"
+ Hexdump.ToHexString(_securityFlags, 2) + ",name=" + Path + "]";
}
}
}

View File

@ -0,0 +1,116 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock
{
internal const int ExclusiveOplockGranted = 1;
internal const int BatchOplockGranted = 2;
internal const int LevelIiOplockGranted = 3;
internal byte OplockLevel;
internal int Fid;
internal int CreateAction;
internal int ExtFileAttributes;
internal int FileType;
internal int DeviceState;
internal long CreationTime;
internal long LastAccessTime;
internal long LastWriteTime;
internal long ChangeTime;
internal long AllocationSize;
internal long EndOfFile;
internal bool Directory;
internal bool IsExtended;
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
OplockLevel = buffer[bufferIndex++];
Fid = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
CreateAction = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
CreationTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastAccessTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastWriteTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ChangeTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ExtFileAttributes = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
AllocationSize = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
EndOfFile = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
FileType = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
DeviceState = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
return bufferIndex - start;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel="
+ OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction
, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime="
+ Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate
(LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x"
+ Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize
+ ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState
+ ",directory=" + Directory + "]";
}
}
}

View File

@ -0,0 +1,70 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNegotiate : ServerMessageBlock
{
private const string Dialects = "\u0002NT LM 0.12\u0000";
public SmbComNegotiate()
{
Command = SmbComNegotiate;
Flags2 = SmbConstants.DefaultFlags2;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
byte[] dialects;
try
{
//dialects = Runtime.GetBytesForString(Dialects, "ASCII");
dialects = Runtime.GetBytesForString(Dialects, "UTF-8");
}
catch (UnsupportedEncodingException)
{
return 0;
}
Array.Copy(dialects, 0, dst, dstIndex, dialects.Length);
return dialects.Length;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount
+ ",dialects=NT LM 0.12]";
}
}
}

View File

@ -0,0 +1,164 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using SharpCifs.Util;
using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNegotiateResponse : ServerMessageBlock
{
internal int DialectIndex;
internal SmbTransport.ServerData Server;
internal SmbComNegotiateResponse(SmbTransport.ServerData server)
{
this.Server = server;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
DialectIndex = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (DialectIndex > 10)
{
return bufferIndex - start;
}
Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF);
Server.Security = Server.SecurityMode & unchecked(0x01);
Server.EncryptedPasswords = (Server.SecurityMode & unchecked(0x02)) == unchecked(
0x02);
Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked(
0x04);
Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked(
0x08);
Server.MaxMpxCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxBufferSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.MaxRawSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.SessionKey = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.Capabilities = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.ServerTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
Server.ServerTimeZone = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF);
return bufferIndex - start;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
{
Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength
);
bufferIndex += Server.EncryptionKeyLength;
if (ByteCount > Server.EncryptionKeyLength)
{
int len = 0;
// TODO: we can use new string routine here
try
{
if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer
[bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{
len += 2;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
, SmbConstants.UniEncoding);
}
else
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)))
{
len++;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
, SmbConstants.OemEncoding);
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
bufferIndex += len;
}
else
{
Server.OemDomainName = "";
}
}
else
{
Server.Guid = new byte[16];
Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16);
Server.OemDomainName = "";
}
// ignore SPNEGO token for now ...
return bufferIndex - start;
}
public override string ToString()
{
return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" +
WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString
(Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share"
: "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount="
+ Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize="
+ Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x"
+ Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString
(Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server
.ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength="
+ Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" +
Server.OemDomainName + "]";
}
}
}

View File

@ -0,0 +1,93 @@
// This code is derived from jcifs smb client library <jcifs at samba dot org>
// Ported by J. Arturo <webmaster at komodosoft dot net>
//
// 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; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal abstract class SmbComNtTransaction : SmbComTransaction
{
private const int NttPrimarySetupOffset = 69;
private const int NttSecondaryParameterOffset = 51;
internal const int NtTransactQuerySecurityDesc = 6;
internal int Function;
public SmbComNtTransaction()
{
// relative to headerStart
primarySetupOffset = NttPrimarySetupOffset;
secondaryParameterOffset = NttSecondaryParameterOffset;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (Command != SmbComNtTransactSecondary)
{
dst[dstIndex++] = MaxSetupCount;
}
else
{
dst[dstIndex++] = unchecked(unchecked(0x00));
}
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(TotalParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(TotalDataCount, dst, dstIndex);
dstIndex += 4;
if (Command != SmbComNtTransactSecondary)
{
WriteInt4(MaxParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(MaxDataCount, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(ParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((ParameterCount == 0 ? 0 : ParameterOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(ParameterDisplacement, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(DataCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((DataCount == 0 ? 0 : DataOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(DataDisplacement, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = unchecked(unchecked(0x00));
}
else
{
// Reserved1
dst[dstIndex++] = unchecked((byte)SetupCount);
WriteInt2(Function, dst, dstIndex);
dstIndex += 2;
dstIndex += WriteSetupWireFormat(dst, dstIndex);
}
return dstIndex - start;
}
}
}

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