Exemplo n.º 1
0
        public void NbtAddressTest()
        {
            //NG: ローカルポートと共に、宛先ポートを変更してしまう。
            //SharpCifs.Config.SetProperty("jcifs.netbios.lport", "2137");

            //ローカルポートのみを変更する。ウェルノウンポートは管理者権限が必要なので。
            SharpCifs.Config.SetProperty("jcifs.smb.client.lport", "8137");
            try
            {
                var lan        = new SmbFile("smb://", "");
                var workgroups = lan.ListFiles();
            }
            catch (Exception ex)
            {
                throw;
            }



            //var nbtAddrs = NbtAddress.GetAllByAddress("COCO4");
            //var nbtAddrs = NbtAddress.GetAllByAddress("127.0.0.1");
            var nbtAddrs = NbtAddress.GetAllByAddress("192.168.254.11");

            foreach (var nbtAddr in nbtAddrs)
            {
                this.Out($"{nbtAddr.GetHostName()} - {nbtAddr.GetInetAddress()}");
            }
        }
Exemplo n.º 2
0
 /// <exception cref="SharpCifs.Smb.SmbException"></exception>
 /// <exception cref="UnknownHostException"></exception>
 public static NtlmChallenge GetChallengeForDomain()
 {
     if (Domain == null)
     {
         throw new SmbException("A domain was not specified");
     }
     lock (Domain)
     {
         long now   = Runtime.CurrentTimeMillis();
         int  retry = 1;
         do
         {
             if (DcListExpiration < now)
             {
                 NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, null);
                 DcListExpiration = now + CachePolicy * 1000L;
                 if (list != null && list.Length > 0)
                 {
                     DcList = list;
                 }
                 else
                 {
                     DcListExpiration = now + 1000 * 60 * 15;
                     if (SmbTransport.LogStatic.Level >= 2)
                     {
                         SmbTransport.LogStatic.WriteLine("Failed to retrieve DC list from WINS");
                     }
                 }
             }
             int max = Math.Min(DcList.Length, LookupRespLimit);
             for (int j = 0; j < max; j++)
             {
                 int i = DcListCounter++ % max;
                 if (DcList[i] != null)
                 {
                     try
                     {
                         return(Interrogate(DcList[i]));
                     }
                     catch (SmbException se)
                     {
                         if (SmbTransport.LogStatic.Level >= 2)
                         {
                             SmbTransport.LogStatic.WriteLine("Failed validate DC: " + DcList[i]);
                             if (SmbTransport.LogStatic.Level > 2)
                             {
                                 Runtime.PrintStackTrace(se, SmbTransport.LogStatic);
                             }
                         }
                     }
                     DcList[i] = null;
                 }
             }
             DcListExpiration = 0;
         }while (retry-- > 0);
         DcListExpiration = now + 1000 * 60 * 15;
     }
     throw new UnknownHostException(
               "Failed to negotiate with a suitable domain controller for " + Domain);
 }
Exemplo n.º 3
0
        public void LanScanTest()
        {
            //Config.GetInt("jcifs.netbios.lport", 137)
            SharpCifs.Config.SetProperty("jcifs.netbios.lport", "8137");

            var hosts = NbtAddress.GetHosts();

            foreach (var nbtAddress in hosts)
            {
                Xb.Util.Out(nbtAddress.GetInetAddress().ToString());
            }
        }
Exemplo n.º 4
0
        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;
        }
Exemplo n.º 5
0
        private static void NameResolutionTest2()
        {
            var naddr = NbtAddress.GetByName($"COCO4");

            Out($"{naddr.GetHostName()}");

            var auth        = new NtlmPasswordAuthentication("", Info.UserName, Info.Password);
            var namedServer = new SmbFile($"smb://{Info.ServerIP}/", auth);
            var exists      = namedServer.Exists();

            var list = namedServer.ListFiles();

            foreach (var smb in list)
            {
                Out($"{smb.GetName()}");
            }
        }
Exemplo n.º 6
0
        public void GetAllByAddressTest()
        {
            //NG: ローカルポートと共に、宛先ポートを変更してしまう。
            //SharpCifs.Config.SetProperty("jcifs.netbios.lport", "2137");

            //ローカルポートのみを変更する。ウェルノウンポートは管理者権限が必要なので。
            SharpCifs.Config.SetProperty("jcifs.smb.client.lport", "2137");

            var srvName1 = Secrets.Get("ServerName");
            var nnames   = NbtAddress.GetAllByAddress(srvName1);

            foreach (var nname in nnames)
            {
                var addrs = nname.GetInetAddress();
                this.Out($"{srvName1} = {addrs}");
            }
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
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;
		}
Exemplo n.º 9
0
        public void GetByNameTest()
        {
            //NG: ローカルポートと共に、宛先ポートを変更してしまう。
            //SharpCifs.Config.SetProperty("jcifs.netbios.lport", "2137");

            //ローカルポートのみを変更する。ウェルノウンポートは管理者権限が必要なので。
            SharpCifs.Config.SetProperty("jcifs.smb.client.lport", "2137");

            var srvName1 = this.ServerName;
            var ipAddr   = this.ServerIp;
            var nname    = NbtAddress.GetByName(srvName1);
            var addrs    = nname.GetInetAddress();

            this.Out($"{srvName1} = {addrs}");
            Assert.AreEqual(ipAddr, addrs.ToString());

            nname = NbtAddress.GetByName(ipAddr);
            addrs = nname.GetInetAddress();
            this.Out($"{ipAddr} = {nname.GetHostName()}");
            Assert.AreEqual(ipAddr, addrs.ToString());
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        /// <exception cref="WinrtCifs.Smb.SmbException"></exception>
        private static NtlmChallenge Interrogate(NbtAddress addr)
        {
            UniAddress   dc    = new UniAddress(addr);
            SmbTransport trans = SmbTransport.GetSmbTransport(dc, 0);

            if (Username == null)
            {
                trans.Connect();
                if (SmbTransport.LogStatic.Level >= 3)
                {
                    SmbTransport.LogStatic.WriteLine("Default credentials (jcifs.smb.client.username/password)"
                                                     + " not specified. SMB signing may not work propertly." + "  Skipping DC interrogation."
                                                     );
                }
            }
            else
            {
                SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default
                                                     );
                ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null);
            }
            return(new NtlmChallenge(trans.Server.EncryptionKey, dc));
        }
Exemplo n.º 12
0
 public override void Run()
 {
     try
     {
         //Ans = new [] { NbtAddress.GetByName(Host, Type, Scope, Svr) };
         Ans = NbtAddress.GetAllByName(Host, Type, Scope, Svr);
     }
     catch (UnknownHostException uhe)
     {
         this.Uhe = uhe;
     }
     catch (Exception ex)
     {
         Uhe = new UnknownHostException(ex.Message);
     }
     finally
     {
         lock (Sem)
         {
             Sem.Count--;
             Runtime.Notify(Sem);
         }
     }
 }
Exemplo n.º 13
0
        /// <exception cref="UnknownHostException"></exception>
        internal static NbtAddress[] LookupServerOrWorkgroup(string name, IPAddress svr)
        {
            Sem         sem  = new Sem(2);
            int         type = NbtAddress.IsWins(svr) ? unchecked (0x1b) : unchecked (0x1d);
            QueryThread q1X  = new QueryThread(sem, name, type, null, svr);
            QueryThread q20  = new QueryThread(sem, name, unchecked (0x20), null, svr);

            q1X.SetDaemon(true);
            q20.SetDaemon(true);
            try
            {
                lock (sem)
                {
                    q1X.Start();
                    q20.Start();

                    while (sem.Count > 0 && q1X.Ans == null && q20.Ans == null)
                    {
                        Runtime.Wait(sem);
                    }
                }
            }
            catch (Exception)
            {
                throw new UnknownHostException(name);
            }
            if (q1X.Ans != null)
            {
                return(q1X.Ans);
            }
            if (q20.Ans != null)
            {
                return(q20.Ans);
            }
            throw q1X.Uhe;
        }
Exemplo n.º 14
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Ssn139()
        {
            Name calledName = new Name(Address.FirstCalledName(), 0x20, null);

            do
            {
                Socket = new SocketEx(AddressFamily.InterNetwork,
                                      SocketType.Stream,
                                      ProtocolType.Tcp);

                //TCPローカルポートは、毎回空いているものを使う。
                //https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
                Socket.Bind(new IPEndPoint(LocalAddr, 0));

                Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
                                              139),
                               SmbConstants.ConnTimeout);

                Socket.SoTimeOut = SmbConstants.SoTimeout;

                Out = Socket.GetOutputStream();
                In  = Socket.GetInputStream();
                SessionServicePacket ssp = new SessionRequestPacket(calledName,
                                                                    NbtAddress.GetLocalName());
                Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
                if (Readn(In, Sbuf, 0, 4) < 4)
                {
                    try
                    {
                        //Socket.`Close` method deleted
                        //Socket.Close();
                        Socket.Dispose();
                    }
                    catch (IOException)
                    {
                    }
                    throw new SmbException("EOF during NetBIOS session request");
                }
                switch (Sbuf[0] & 0xFF)
                {
                case SessionServicePacket.PositiveSessionResponse:
                {
                    if (Log.Level >= 4)
                    {
                        Log.WriteLine("session established ok with " + Address);
                    }
                    return;
                }

                case SessionServicePacket.NegativeSessionResponse:
                {
                    int errorCode = In.Read() & 0xFF;
                    switch (errorCode)
                    {
                    case NbtException.CalledNotPresent:
                    case NbtException.NotListeningCalled:
                    {
                        //Socket.`Close` method deleted
                        //Socket.Close();
                        Socket.Dispose();
                        break;
                    }

                    default:
                    {
                        Disconnect(true);
                        throw new NbtException(NbtException.ErrSsnSrvc,
                                               errorCode);
                    }
                    }
                    break;
                }

                case -1:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc,
                                           NbtException.ConnectionRefused);
                }

                default:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, 0);
                }
                }
            }while ((calledName.name = Address.NextCalledName()) != null);
            throw new IOException("Failed to establish session with " + Address);
        }
Exemplo n.º 15
0
        /// <exception cref="UnknownHostException"></exception>
        public static UniAddress[] GetAllByName(string hostname, bool possibleNtDomainOrWorkgroup)
        {
            object addr;
            int    i;

            if (string.IsNullOrEmpty(hostname))
            {
                throw new UnknownHostException();
            }
            if (IsDotQuadIp(hostname))
            {
                UniAddress[] addrs = new UniAddress[1];
                addrs[0] = new UniAddress(NbtAddress.GetByName(hostname));
                return(addrs);
            }
            for (i = 0; i < _resolveOrder.Length; i++)
            {
                try
                {
                    switch (_resolveOrder[i])
                    {
                    case ResolverLmhosts:
                    {
                        if ((addr = Lmhosts.GetByName(hostname)) == null)
                        {
                            continue;
                        }
                        break;
                    }

                    case ResolverWins:
                    {
                        if (hostname == NbtAddress.MasterBrowserName ||
                            hostname.Length > 15)
                        {
                            // invalid netbios name
                            continue;
                        }
                        if (possibleNtDomainOrWorkgroup)
                        {
                            addr = LookupServerOrWorkgroup(hostname,
                                                           NbtAddress.GetWinsAddress());
                        }
                        else
                        {
                            addr = NbtAddress.GetByName(hostname,
                                                        unchecked (0x20),
                                                        null,
                                                        NbtAddress.GetWinsAddress());
                        }
                        break;
                    }

                    case ResolverBcast:
                    {
                        if (hostname.Length > 15)
                        {
                            // invalid netbios name
                            continue;
                        }

                        try
                        {
                            if (possibleNtDomainOrWorkgroup)
                            {
                                NbtAddress[] iaddrs = LookupServerOrWorkgroup(hostname,
                                                                              _baddr);

                                UniAddress[] addrs = new UniAddress[iaddrs.Length];
                                for (int ii = 0; ii < iaddrs.Length; ii++)
                                {
                                    addrs[ii] = new UniAddress(iaddrs[ii]);
                                }
                                return(addrs);
                            }
                            else
                            {
                                addr = NbtAddress.GetByName(hostname,
                                                            unchecked (0x20),
                                                            null,
                                                            _baddr);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (i == _resolveOrder.Length - 1)
                            {
                                throw ex;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        break;
                    }

                    case ResolverDns:
                    {
                        if (IsAllDigits(hostname))
                        {
                            throw new UnknownHostException(hostname);
                        }

                        IPAddress[] iaddrs = Extensions.GetAddressesByName(hostname);

                        if (iaddrs == null || iaddrs.Length == 0)
                        {
                            continue;
                        }

                        return(iaddrs.Select(iaddr => new UniAddress(iaddr)).ToArray());
                    }

                    default:
                    {
                        // Success
                        throw new UnknownHostException(hostname);
                    }
                    }
                    UniAddress[] addrs1 = new UniAddress[1];
                    addrs1[0] = new UniAddress(addr);
                    return(addrs1);
                }
                catch (IOException)
                {
                }
            }
            // Success
            // Failure
            throw new UnknownHostException(hostname);
        }
Exemplo n.º 16
0
        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;
        }
Exemplo n.º 17
0
        static UniAddress()
        {
            string    ro   = Config.GetProperty("jcifs.resolveOrder");
            IPAddress nbns = NbtAddress.GetWinsAddress();

            try
            {
                _baddr = Config.GetInetAddress("jcifs.netbios.baddr",
                                               Extensions.GetAddressByName("255.255.255.255"));
            }
            catch (UnknownHostException)
            {
            }
            if (string.IsNullOrEmpty(ro))
            {
                if (nbns == null)
                {
                    _resolveOrder    = new int[3];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverDns;
                    _resolveOrder[2] = ResolverBcast;
                }
                else
                {
                    _resolveOrder    = new int[4];
                    _resolveOrder[0] = ResolverLmhosts;
                    _resolveOrder[1] = ResolverWins;
                    _resolveOrder[2] = ResolverDns;
                    _resolveOrder[3] = ResolverBcast;
                }
            }
            else
            {
                int[]           tmp = new int[4];
                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 (nbns == null)
                            {
                                if (_log.Level > 1)
                                {
                                    _log.WriteLine(
                                        "UniAddress 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"))
                                {
                                    tmp[i++] = ResolverDns;
                                }
                                else
                                {
                                    if (_log.Level > 1)
                                    {
                                        _log.WriteLine("unknown resolver method: " + s);
                                    }
                                }
                            }
                        }
                    }
                }
                _resolveOrder = new int[i];
                Array.Copy(tmp, 0, _resolveOrder, 0, i);
            }
        }
Exemplo n.º 18
0
        /// <exception cref="System.IO.IOException"></exception>
        internal virtual void Ssn139()
        {
            Name calledName = new Name(Address.FirstCalledName(), 0x20, null
                                       );

            do
            {
                Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (LocalAddr != null)
                {
                    Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
                }
                Socket.Connect(Address.GetHostAddress(), 139);
                //Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout);
                Socket.SoTimeOut = SmbConstants.SoTimeout;

                Out = Socket.GetOutputStream();
                In  = Socket.GetInputStream();
                SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName
                                                                        ());
                Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
                if (Readn(In, Sbuf, 0, 4) < 4)
                {
                    try
                    {
                        Socket.Dispose();
                    }
                    catch (IOException)
                    {
                    }
                    throw new SmbException("EOF during NetBIOS session request");
                }
                switch (Sbuf[0] & 0xFF)
                {
                case SessionServicePacket.PositiveSessionResponse:
                {
                    if (Log.Level >= 4)
                    {
                        Log.WriteLine("session established ok with " + Address);
                    }
                    return;
                }

                case SessionServicePacket.NegativeSessionResponse:
                {
                    int errorCode = In.Read() & 0xFF;
                    switch (errorCode)
                    {
                    case NbtException.CalledNotPresent:
                    case NbtException.NotListeningCalled:
                    {
                        Socket.Dispose();
                        break;
                    }

                    default:
                    {
                        Disconnect(true);
                        throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
                    }
                    }
                    break;
                }

                case -1:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
                                           );
                }

                default:
                {
                    Disconnect(true);
                    throw new NbtException(NbtException.ErrSsnSrvc, 0);
                }
                }
            }while ((calledName.name = Address.NextCalledName()) != null);
            throw new IOException("Failed to establish session with " + Address);
        }