示例#1
1
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy)
        {
            // TODO: make it extension method.
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            return OctetString.Empty;
        }
示例#3
0
        /// <summary>
        /// Creates a <see cref="SetRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version</param>
        /// <param name="community">Community name</param>
        /// <param name="variables">Variables</param>
        public SetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("only v1 and v2c are supported", "version");
            }
            
            Version = version;
            Header = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new SetRequestPdu(
                requestId,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;
 
            _bytes = this.PackMessage(null).ToBytes();
        }
        public GetResponseMessage(int requestId, VersionCode version, OctetString community, ErrorCode error, int index, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("Please use overload constructor for v3", "version");
            }

            Version = version;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            GetResponsePdu pdu = new GetResponsePdu(
                requestId,
                error,
                index,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
示例#5
0
        internal static AgentProfile Create(Guid id, VersionCode version, IPEndPoint agent, string getCommunity, string setCommunity, string agentName, string authenticationPassphrase, string privacyPassphrase, int authenticationMethod, int privacyMethod, string userName, int timeout)
        {
            if (version == VersionCode.V3)
            {
                return new SecureAgentProfile(
                    id, 
                    version,
                    agent, 
                    agentName,
                    authenticationPassphrase, 
                    privacyPassphrase,
                    authenticationMethod, 
                    privacyMethod,
                    userName, 
                    timeout);
            }

            return new NormalAgentProfile(
                id, 
                version,
                agent, 
                new OctetString(getCommunity),
                new OctetString(setCommunity), 
                agentName,
                userName, 
                timeout);
        }
        /// <summary>
        /// Creates a <see cref="SetRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version</param>
        /// <param name="community">Community name</param>
        /// <param name="variables">Variables</param>
        public SetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("only v1 and v2c are supported", "version");
            }
            
            Version = version;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            SetRequestPdu pdu = new SetRequestPdu(
                requestId,
                ErrorCode.NoError,
                0,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;
 
            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportMessage"/> class.
        /// </summary>
        /// <param name="version">The version code.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The security parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="length">The length bytes.</param>
        public ReportMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }
            
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }
            
            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }
            
            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            Version = version;
            Header = header;
            Parameters = parameters;
            Scope = scope;
            Privacy = privacy;
            Privacy.AuthenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);            
            _bytes = this.PackMessage(length).ToBytes();
        }
        public SecureAgentProfile(Guid id, VersionCode version, IPEndPoint agent, string agentName, string authenticationPassphrase, string privacyPassphrase, int authenticationMethod, int privacyMethod, string userName, int timeout)
            : base(id, version, agent, agentName, userName, timeout)
        {
            AuthenticationPassphrase = authenticationPassphrase;
            PrivacyPassphrase = privacyPassphrase;
            AuthenticationMethod = authenticationMethod;
            PrivacyMethod = privacyMethod;

            switch (AuthenticationMethod)
            {
                case 0:
                    _auth = DefaultAuthenticationProvider.Instance;
                    break;
                case 1:
                    _auth = new MD5AuthenticationProvider(new OctetString(AuthenticationPassphrase));
                    break;
                case 2:
                    _auth = new SHA1AuthenticationProvider(new OctetString(AuthenticationPassphrase));
                    break;
            }

            switch (PrivacyMethod)
            {
                case 0:
                    _privacy = new DefaultPrivacyProvider(_auth);
                    break;
                case 1:
                    _privacy = new DESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth);
                    break;
                case 2:
                    _privacy = new AESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth);
                    break;
            }
        }
 internal static Sequence PackMessage(VersionCode version, ISegment header, SecurityParameters parameters, ISegment scope, IPrivacyProvider privacy)
 {
     if (scope == null)
     {
         throw new ArgumentNullException("scope");
     }
     
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     
     if (header == null)
     {
         throw new ArgumentNullException("header");
     }
     
     if (privacy == null)
     {
         throw new ArgumentNullException("privacy");
     }
     
     ISnmpData[] collection = new ISnmpData[4]
                                      {
                                          new Integer32((int)version),
                                          header.GetData(version),
                                          parameters.GetData(version),
                                          privacy.Encrypt(scope.GetData(version), parameters)
                                      };
     return new Sequence(collection);
 }
示例#10
0
 internal AgentProfile(Guid id, VersionCode version, IPEndPoint agent, string name, string userName, int timeout)
 {
     Timeout = timeout;
     Id = id;
     UserName = userName;
     VersionCode = version;
     Agent = agent;
     Name = name;
 }
        public SnmpPoller(ListView resultlist, ListView cpuresultlist)
        {
            HostName = "localhost";
            SnmpPort = 161;
            SnmpCommunity = "public";
            SnmpVersion = VersionCode.V2;
            SnmpUser = string.Empty;
            SnmpPassword = string.Empty;

            SnmpTimeout = 1000;
            SnmpRetry = 0;
            results = new ListView.ListViewItemCollection(resultlist);
            CpuResults = new ListView.ListViewItemCollection(cpuresultlist);
        }
示例#12
0
 public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList<Variable> variables)
 {
     if (variables == null)
     {
         throw new ArgumentNullException("variables");
     }
     
     if (enterprise == null)
     {
         throw new ArgumentNullException("enterprise");
     }
     
     if (community == null)
     {
         throw new ArgumentNullException("community");
     }
     
     if (agent == null)
     {
         throw new ArgumentNullException("agent");
     }
     
     if (version != VersionCode.V1)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", version), "version");
     }
     
     Version = version;
     AgentAddress = agent;
     Community = community;
     Enterprise = enterprise;
     Generic = generic;
     Specific = specific;
     TimeStamp = time;
     var pdu = new TrapV1Pdu(
         Enterprise,
         new IP(AgentAddress),
         new Integer32((int)Generic),
         new Integer32(Specific),
         new TimeTicks(TimeStamp),
         variables);
     _pdu = pdu;
     Parameters = SecurityParameters.Create(Community);
 }
        public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (agent == null)
            {
                throw new ArgumentNullException("agent");
            }
            
            Version = version;
            AgentAddress = agent;
            Community = community;
            Variables = variables;
            Enterprise = enterprise;
            Generic = generic;
            Specific = specific;
            TimeStamp = time;
            TrapV1Pdu pdu = new TrapV1Pdu(
                Enterprise,
                new IP(AgentAddress),
                new Integer32((int)Generic),
                new Integer32(Specific),
                new TimeTicks(TimeStamp),
                Variables);
            Parameters = new SecurityParameters(null, null, null, Community, null, null);

            _bytes = SnmpMessageExtension.PackMessage(Version, Community, pdu).ToBytes();
        }
        /// <summary>
        /// Creates a <see cref="GetBulkRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request ID.</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="community">Community name.</param>
        /// <param name="nonRepeaters">Non-repeaters.</param>
        /// <param name="maxRepetitions">Max repetitions.</param>
        /// <param name="variables">Variables.</param>
        public GetBulkRequestMessage(int requestId, VersionCode version, OctetString community, int nonRepeaters, int maxRepetitions, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version != VersionCode.V2)
            {
                throw new ArgumentException("only v2c are supported", "version");
            }

            if (nonRepeaters > variables.Count)
            {
                throw new ArgumentException("nonRepeaters should not be greater than variable count", "nonRepeaters");
            }

            if (maxRepetitions < 1)
            {
                throw new ArgumentException("maxRepetitions should be greater than 0", "maxRepetitions");
            }

            Version = version;
            Header = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new GetBulkRequestPdu(
                requestId,
                nonRepeaters,
                maxRepetitions,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = this.PackMessage(null).ToBytes();
        }
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="provider">The authentication provider.</param>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        public static void ComputeHash(this IAuthenticationProvider provider, VersionCode version, Header header, SecurityParameters parameters, ISegment scope, IPrivacyProvider privacy)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            if (provider is DefaultAuthenticationProvider)
            {
                return;
            }

            if (0 == (header.SecurityLevel & Levels.Authentication))
            {
                return;
            }

            var scopeData = privacy.GetScopeData(header, parameters, scope.GetData(version));
            parameters.AuthenticationParameters = provider.ComputeHash(version, header, parameters, scopeData, privacy, null); // replace the hash.
        }
        public InformRequestMessage(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("only v1 and v2c are supported", "version");
            }
            
            Version = version;
            Enterprise = enterprise;
            TimeStamp = time;
            Header = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new InformRequestPdu(
                requestId,
                enterprise,
                time,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = this.PackMessage(null).ToBytes();
        }
        public TrapV2Message(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version != VersionCode.V2)
            {
                throw new ArgumentException("only v2c are supported", "version");
            }
            
            Version = version;
            Enterprise = enterprise;
            TimeStamp = time;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            TrapV2Pdu pdu = new TrapV2Pdu(
                requestId,
                enterprise,
                time,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = SnmpMessageExtension.PackMessage(Version, Community, pdu).ToBytes();
        }
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            return(ComputeHash(version, header, parameters, privacy.Encrypt(scope.GetData(version), parameters), privacy));
        }
        /// <summary>
        /// Verifies the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scopeBytes">The scope bytes.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <returns></returns>
        public bool VerifyHash(VersionCode version, Header header, SecurityParameters parameters, ISnmpData scopeBytes, IPrivacyProvider privacy)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (scopeBytes == null)
            {
                throw new ArgumentNullException("scopeBytes");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            return(true);
        }
示例#20
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static int Walk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, int timeout, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            var      result = 0;
            var      tableV = new Variable(table);
            Variable seed;
            var      next        = tableV;
            var      rowMask     = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var      subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);

            do
            {
                seed = next;
                if (seed == tableV)
                {
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }
            }while (HasNext(version, endpoint, community, seed, timeout, out next));
            return(result);
        }
示例#21
0
        /// <summary>
        /// Sets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList <Variable> Set(VersionCode version, IPEndPoint endpoint, OctetString community, IList <Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message  = new SetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu      = response.Pdu();

            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          endpoint.Address,
                          response);
            }

            return(pdu.Variables);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ResponseMessage"/> class.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="needAuthentication">if set to <c>true</c>, authentication is needed.</param>
        /// <param name="length">The length bytes.</param>
        public ResponseMessage(
            VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, bool needAuthentication, byte[] length)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            Version    = version;
            Header     = header;
            Parameters = parameters;
            Scope      = scope;
            Privacy    = privacy;

            if (needAuthentication)
            {
                Privacy.AuthenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            }

            _bytes = this.PackMessage(length).ToBytes();
        }
示例#23
0
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The scope data.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="length">The length bytes.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy, byte[] length)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            return(OctetString.Empty);
        }
示例#24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportMessage"/> class.
        /// </summary>
        /// <param name="version">The version code.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The security parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        public ReportMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            Version     = version;
            Header      = header;
            _parameters = parameters;
            Scope       = scope;
            _privacy    = privacy;

            Parameters.AuthenticationParameters = Privacy.AuthenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
示例#25
0
        private static bool HasNext(VersionCode version, IPEndPoint endpoint, OctetString community, Variable seed, int timeout, out Variable next)
        {
            if (seed == null)
            {
                throw new ArgumentNullException("seed");
            }

            List <Variable> variables = new List <Variable> {
                new Variable(seed.Id)
            };

            GetNextRequestMessage message = new GetNextRequestMessage(
                RequestCounter.NextId,
                version,
                community,
                variables);

            ISnmpMessage response   = message.GetResponse(timeout, endpoint);
            var          pdu        = response.Pdu;
            bool         errorFound = pdu.ErrorStatus.ToErrorCode() == ErrorCode.NoSuchName;

            next = errorFound ? null : pdu.Variables[0];
            return(!errorFound);
        }
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The scope data.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="length">The length bytes.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy, byte[] length)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            return OctetString.Empty;
        }
示例#27
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static int BulkWalk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var tableV = new Variable(table);
            var seed = tableV;
            IList<Variable> next;
            var result = 0;
            var message = report;
            while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
            }

        end:
            return result;
        }
示例#28
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static int Walk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var result = 0;
            var tableV = new Variable(table);
            Variable seed;
            var next = tableV;
            var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
            do
            {
                seed = next;
                if (seed == tableV)
                {
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }
            }
            while (HasNext(version, endpoint, community, seed, timeout, out next));
            return result;
        }
示例#29
0
        public static void SendInform(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList <Variable> variables, int timeout, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException(nameof(receiver));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException(nameof(enterprise));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            if (version == VersionCode.V3 && privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            if (version == VersionCode.V3 && report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            var message = version == VersionCode.V3
                                    ? new InformRequestMessage(
                version,
                MessageCounter.NextId,
                requestId,
                community,
                enterprise,
                timestamp,
                variables,
                privacy,
                MaxMessageSize,
                report)
                                    : new InformRequestMessage(
                requestId,
                version,
                community,
                enterprise,
                timestamp,
                variables);

            var response = message.GetResponse(timeout, receiver);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          receiver.Address,
                          response);
            }
        }
 public GetBulkRequestMessage(
     VersionCode version, int messageId, int requestId, OctetString userName, int nonRepeaters, int maxRepetitions, IList <Variable> variables,
     IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, nonRepeaters, maxRepetitions, variables, privacy, 0xFFE3, report)
 {
 }
示例#31
0
        private static bool BulkHasNext(VersionCode version, IPEndPoint receiver, OctetString community, Variable seed, int timeout, int maxRepetitions, out IList <Variable> next, IPrivacyProvider privacy, ref ISnmpMessage report)
        {
            if (version == VersionCode.V1)
            {
                throw new NotSupportedException("SNMP v1 is not supported");
            }

            var variables = new List <Variable> {
                new Variable(seed.Id)
            };
            var request = version == VersionCode.V3
                                                ? new GetBulkRequestMessage(
                version,
                MessageCounter.NextId,
                RequestCounter.NextId,
                community,
                0,
                maxRepetitions,
                variables,
                privacy,
                MaxMessageSize,
                report)
                                                : new GetBulkRequestMessage(
                RequestCounter.NextId,
                version,
                community,
                0,
                maxRepetitions,
                variables);
            var reply = request.GetResponse(timeout, receiver);

            if (reply is ReportMessage)
            {
                if (reply.Pdu().Variables.Count == 0)
                {
                    // TODO: whether it is good to return?
                    next = new List <Variable>(0);
                    return(false);
                }

                var id = reply.Pdu().Variables[0].Id;
                if (id != IdNotInTimeWindow)
                {
                    // var error = id.GetErrorMessage();
                    // TODO: whether it is good to return?
                    next = new List <Variable>(0);
                    return(false);
                }

                // according to RFC 3414, send a second request to sync time.
                request = new GetBulkRequestMessage(
                    version,
                    MessageCounter.NextId,
                    RequestCounter.NextId,
                    community,
                    0,
                    maxRepetitions,
                    variables,
                    privacy,
                    MaxMessageSize,
                    reply);
                reply = request.GetResponse(timeout, receiver);
            }
            else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          receiver.Address,
                          reply);
            }

            next   = reply.Pdu().Variables;
            report = request;
            return(next.Count != 0);
        }
        /// <summary>
        /// Creates a <see cref="GetBulkRequestMessage"/> with a specific <see cref="Sequence"/>.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="requestId">The request id.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="contextName">Name of context.</param>
        /// <param name="nonRepeaters">The non repeaters.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="maxMessageSize">Size of the max message.</param>
        /// <param name="report">The report.</param>
        public GetBulkRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, OctetString contextName, int nonRepeaters, int maxRepetitions, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }

            if (contextName == null)
            {
                throw new ArgumentNullException("contextName");
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            if (report == null)
            {
                throw new ArgumentNullException("report");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            if (nonRepeaters > variables.Count)
            {
                throw new ArgumentException("nonRepeaters should not be greater than variable count", "nonRepeaters");
            }

            if (maxRepetitions < 1)
            {
                throw new ArgumentException("maxRepetitions should be greater than 0", "maxRepetitions");
            }

            Version = version;
            Privacy = privacy;

            // TODO: define more constants.
            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
            var parameters = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;
            Parameters = new SecurityParameters(
                parameters.EngineId,
                parameters.EngineBoots,
                parameters.EngineTime,
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new GetBulkRequestPdu(
                requestId,
                nonRepeaters,
                maxRepetitions,
                variables);
            var scope = report.Scope;
            var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;
            Scope = new Scope(contextEngineId, contextName, pdu);

            authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = this.PackMessage(null).ToBytes();
        }
 public static async Task <IList <Variable> > Set(VersionCode version, IPEndPoint endpoint, OctetString community, IList <Variable> variables)
 {
     throw new InvalidOperationException("Obsolete method");
 }
示例#34
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      contextName    = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("C:", "Context name", delegate(string v) { contextName = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v|version:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                if (v == "2c")
                {
                    v = "2";
                }

                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            })
                          .Add("m|mode:", "WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 1 || extra.Count > 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyVersionAttribute>().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                var addresses = Dns.GetHostAddressesAsync(extra[0]);
                addresses.Wait();
                foreach (IPAddress address in
                         addresses.Result.Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty: contextName), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    if (string.IsNullOrEmpty(user))
                    {
                        Console.WriteLine("User name need to be specified for v3.");
                        return;
                    }

                    IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                        ? GetAuthenticationProviderByName(authentication, authPhrase)
                        : DefaultAuthenticationProvider.Instance;
                    IPrivacyProvider priv;
                    if ((level & Levels.Privacy) == Levels.Privacy)
                    {
                        if (DESPrivacyProvider.IsSupported)
                        {
                            priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                        }
                        else
                        {
                            Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                            return;
                        }
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);
                    Messenger.BulkWalk(version, receiver, new OctetString(user), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty : contextName), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
示例#35
0
        public TrapV2Message(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, OctetString engineId, int engineBoots, int engineTime)
        {
            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }

            if (engineId == null)
            {
                throw new ArgumentNullException("engineId");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            Version    = version;
            Privacy    = privacy;
            Enterprise = enterprise;
            TimeStamp  = time;
            Levels recordToSecurityLevel = PrivacyProviderExtension.ToSecurityLevel(privacy);
            byte   b = (byte)recordToSecurityLevel;

            // TODO: define more constants.
            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), new OctetString(new[] { b }), new Integer32(3));
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                engineId,
                new Integer32(engineBoots),
                new Integer32(engineTime),
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new TrapV2Pdu(
                requestId,
                enterprise,
                time,
                variables);

            Scope = new Scope(OctetString.Empty, OctetString.Empty, pdu);

            Parameters.AuthenticationParameters = authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
示例#36
0
        private static bool BulkHasNext(VersionCode version, IPEndPoint receiver, OctetString community, Variable seed, int timeout, int maxRepetitions, out IList<Variable> next, IPrivacyProvider privacy, ref ISnmpMessage report)
        {
            if (version == VersionCode.V1)
            {
                throw new ArgumentException("v1 is not supported", "version");
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var request = version == VersionCode.V3
                                                ? new GetBulkRequestMessage(
                                                      version,
                                                      MessageCounter.NextId,
                                                      RequestCounter.NextId,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables,
                                                      privacy,
                                                      MaxMessageSize,
                                                      report)
                                                : new GetBulkRequestMessage(
                                                      RequestCounter.NextId,
                                                      version,
                                                      community,
                                                      0,
                                                      maxRepetitions,
                                                      variables);
            var reply = request.GetResponse(timeout, receiver);
            if (reply is ReportMessage)
            {
                if (reply.Pdu().Variables.Count == 0)
                {
                    // TODO: whether it is good to return?
                    next = new List<Variable>(0);
                    return false;
                }

                var id = reply.Pdu().Variables[0].Id;
                if (id != IdNotInTimeWindow)
                {
                    // var error = id.GetErrorMessage();
                    // TODO: whether it is good to return?
                    next = new List<Variable>(0);
                    return false;
                }

                // according to RFC 3414, send a second request to sync time.
                request = new GetBulkRequestMessage(
                    version,
                    MessageCounter.NextId,
                    RequestCounter.NextId,
                    community,
                    0,
                    maxRepetitions,
                    variables,
                    privacy,
                    MaxMessageSize,
                    reply);
                reply = request.GetResponse(timeout, receiver);
            }
            else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    reply);
            }

            next = reply.Pdu().Variables;
            report = request;
            return next.Count != 0;
        }
示例#37
0
        /// <summary>
        /// Get SNMP Printer Satate
        /// </summary>
        /// <param name="ipAddress">IPAddress of host</param>
        /// <returns>SNMPPrinterStateModel</returns>
        SNMPPrinterStateModel SNMPGet(VersionCode version, IPEndPoint ipEndPoint, OctetString community, int timeout)
        {
            /*string SerialNumber = "";
             * string DisplayMessage = "";
             * string AlertMessage = "";
             * string ContactInfo = "";
             * string LocationInfo = "";
             * string Model = "";
             *
             * int PageCount = 0;
             * string Uptime = "";*/

            SNMPPrinterStateModel snmpPrinterStateModel = new SNMPPrinterStateModel();

            List <Variable> variable = new List <Variable>();

            variable.Add(new Variable(new ObjectIdentifier("1.3.6.1.4.1.641.2.1.2.1.6.1")));  // SerialNumber for Lexmark
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.5.1.1.17.1")));   // SerialNumber for Xerox
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.16.5.1.2.1.1"))); //DisplayMessage
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.16.5.1.2.1.2"))); //DisplayMessage2
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.10.2.1.4.1.1"))); //PageCount
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.1.3.0")));           //Uptime
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.1.4.0")));           //ContactInfo
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.1.6.0")));           //LocationInfo
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.4.1.641.2.1.2.1.2.1"))); // Model for Lexmark
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.25.3.2.1.3.1")));    //Model for Xerox

            try
            {
                var result = Messenger.Get(version,
                                           ipEndPoint,
                                           community,
                                           variable,
                                           timeout);
                if (result != null)
                {
                    if (result[0].Data.ToString() != "NoSuchObject")
                    {
#if DEBUG
                        Console.WriteLine("SerialNumber=" + result[0].Data.ToString());
#endif
                        snmpPrinterStateModel.SerialNumber = result[0].Data.ToString();
                    }
                    else
                    {
#if DEBUG
                        Console.WriteLine("SerialNumber=" + UTFtoASCII(result[1].Data));
#endif
                        snmpPrinterStateModel.SerialNumber = result[1].Data.ToString();
                    }
                    if (result[8].Data.ToString() != "NoSuchObject")
                    {
#if DEBUG
                        Console.WriteLine("Model=" + result[8].Data.ToString());
#endif
                        snmpPrinterStateModel.Model = result[8].Data.ToString();
                    }
                    else
                    {
#if DEBUG
                        Console.WriteLine("Model=" + UTFtoASCII(result[9].Data));
#endif
                        snmpPrinterStateModel.Model = result[9].Data.ToString();
                    }
                    snmpPrinterStateModel.ContactInfo  = UTFtoASCII(result[6].Data);
                    snmpPrinterStateModel.LocationInfo = UTFtoASCII(result[7].Data);
#if DEBUG
                    Console.WriteLine("PageCount=" + result[4].Data.ToString());
#endif
                    snmpPrinterStateModel.PageCount = Convert.ToInt32(result[4].Data.ToString());
#if DEBUG
                    Console.WriteLine("Uptime=" + result[5].Data.ToString());
#endif
                    snmpPrinterStateModel.Uptime = result[5].Data.ToString();
#if DEBUG
                    Console.WriteLine("DisplayMessage=" + UTFtoASCII(result[2].Data));
#endif
                    snmpPrinterStateModel.DisplayMessage = UTFtoASCII(result[2].Data);
#if DEBUG
                    Console.WriteLine("Begin DisplayMessage2");
                    Console.WriteLine("DisplayMessage2=" + UTFtoASCII(result[3].Data));
#endif
                    snmpPrinterStateModel.DisplayMessage += " " + UTFtoASCII(result[3].Data);
                }
            }
            catch
            {
#if DEBUG
                Console.WriteLine("EEEEEEERRRRRRRROOOOOOOOORRRRRRRRR!!!");
#endif
            }
            return(snmpPrinterStateModel);
        }
示例#38
0
        private static ISnmpMessage ParseMessage(int first, Stream stream, UserRegistry registry)
        {
            ISnmpData array = DataFactory.CreateSnmpData(first, stream);

            if (array == null)
            {
                return(null);
            }

            if (array.TypeCode != SnmpType.Sequence)
            {
                throw new SnmpException("not an SNMP message");
            }

            Sequence body = (Sequence)array;

            if (body.Length != 3 && body.Length != 4)
            {
                throw new SnmpException("not an SNMP message");
            }

            VersionCode        version = (VersionCode)((Integer32)body[0]).ToInt32();
            Header             header;
            SecurityParameters parameters;
            IPrivacyProvider   privacy;
            Scope scope;

            if (body.Length == 3)
            {
                header     = Header.Empty;
                parameters = SecurityParameters.Create((OctetString)body[1]);
                privacy    = DefaultPrivacyProvider.DefaultPair;
                scope      = new Scope((ISnmpPdu)body[2]);
            }
            else
            {
                header     = new Header(body[1]);
                parameters = new SecurityParameters((OctetString)body[2]);
                privacy    = registry.Find(parameters.UserName);
                if (privacy == null)
                {
                    // handle decryption exception.
                    return(new MalformedMessage(header.MessageId, parameters.UserName));
                }

                var code = body[3].TypeCode;
                if (code == SnmpType.Sequence)
                {
                    // v3 not encrypted
                    scope = new Scope((Sequence)body[3]);
                }
                else if (code == SnmpType.OctetString)
                {
                    // v3 encrypted
                    try
                    {
                        scope = new Scope((Sequence)privacy.Decrypt(body[3], parameters));
                    }
                    catch (DecryptionException)
                    {
                        // handle decryption exception.
                        return(new MalformedMessage(header.MessageId, parameters.UserName));
                    }
                }
                else
                {
                    throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "invalid v3 packets scoped data: {0}", code));
                }

                if (!privacy.AuthenticationProvider.VerifyHash(version, header, parameters, body[3], privacy))
                {
                    throw new SnmpException("invalid v3 packet data hash detected");
                }
            }

            var scopeCode = scope.Pdu.TypeCode;

            switch (scopeCode)
            {
            case SnmpType.TrapV1Pdu:
                return(new TrapV1Message(body));

            case SnmpType.TrapV2Pdu:
                return(new TrapV2Message(version, header, parameters, scope, privacy));

            case SnmpType.GetRequestPdu:
                return(new GetRequestMessage(version, header, parameters, scope, privacy));

            case SnmpType.ResponsePdu:
                return(new ResponseMessage(version, header, parameters, scope, privacy, false));

            case SnmpType.SetRequestPdu:
                return(new SetRequestMessage(version, header, parameters, scope, privacy));

            case SnmpType.GetNextRequestPdu:
                return(new GetNextRequestMessage(version, header, parameters, scope, privacy));

            case SnmpType.GetBulkRequestPdu:
                return(new GetBulkRequestMessage(version, header, parameters, scope, privacy));

            case SnmpType.ReportPdu:
                return(new ReportMessage(version, header, parameters, scope, privacy));

            case SnmpType.InformRequestPdu:
                return(new InformRequestMessage(version, header, parameters, scope, privacy));

            default:
                throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "unsupported pdu: {0}", scopeCode));
            }
        }
示例#39
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new UdpClient(addressFamily))
            {
                #if (!CF)
                udp.EnableBroadcast = true;
                #endif
                udp.Send(bytes, bytes.Length, broadcastAddress);

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                #if CF
                _bufferSize = 8192;
                #else
                _bufferSize = udp.Client.ReceiveBufferSize;
                #endif

                #if ASYNC
                Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client));
                #else
                Task.Factory.StartNew(() => AsyncReceive(udp.Client));
                #endif

                Thread.Sleep(interval);
                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Close();
            }
        }
示例#40
0
        public static void SendInform(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList<Variable> variables, int timeout, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3 && privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            if (version == VersionCode.V3 && report == null)
            {
                throw new ArgumentNullException("report");
            }

            var message = version == VersionCode.V3
                                    ? new InformRequestMessage(
                                          version,
                                          MessageCounter.NextId,
                                          requestId,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables,
                                          privacy,
                                          MaxMessageSize,
                                          report)
                                    : new InformRequestMessage(
                                          requestId,
                                          version,
                                          community,
                                          enterprise,
                                          timestamp,
                                          variables);

            var response = message.GetResponse(timeout, receiver);
            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    receiver.Address,
                    response);
            }
        }
示例#41
0
        public static void FixHelper(string HelperName, int MajorVersion, int MinorVersion)
        {
            StringBuilder PathShell = new StringBuilder(260);

            try
            {
                string HelperFileName = AscomDirectory + @"\" + HelperName;
                LogMessage("FixHelper", "Ensuring " + HelperName + " is a Platform 5 version: " + HelperFileName);
                FileVersionInfo FVInfo = FileVersionInfo.GetVersionInfo(HelperFileName);
                LogMessage("FixHelper", "  Found version : " + FVInfo.FileMajorPart.ToString() + "." + FVInfo.FileMinorPart.ToString() + "." + FVInfo.FileBuildPart.ToString() + "." + FVInfo.FilePrivatePart.ToString());
                if ((((FVInfo.FileMajorPart * 0x1000) + FVInfo.FileMinorPart) > ((MajorVersion * 0x1000) + MinorVersion))) // Version is not 5.0.x.x so replace
                {
                    LogMessage("FixHelper", "  File does not match required version number: " + MajorVersion.ToString() + "." + MinorVersion.ToString() + ".x.x, restoring original Platform 5 file");
                    try
                    {
                        File.Copy(HelperName, HelperFileName, true); // Copy from the installer directory to the ASCOM directory on this system
                        LogMessage("FixHelper", "  File copied OK");
                        FVInfo = FileVersionInfo.GetVersionInfo(HelperFileName);
                        LogMessage("FixHelper", "  Restored version : " + FVInfo.FileMajorPart.ToString() + "." + FVInfo.FileMinorPart.ToString() + "." + FVInfo.FileBuildPart.ToString() + "." + FVInfo.FilePrivatePart.ToString());
                        if ((((FVInfo.FileMajorPart * 0x1000) + FVInfo.FileMinorPart) > ((MajorVersion * 0x1000) + MinorVersion))) // Version is not 5.0.x.x so replace
                        {
                            LogMessage("FixHelper", "  ERROR incorrect file still in place!");
                        }
                        else
                        {
                            LogMessage("FixHelper", "  OK correct file now in place");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogError("FixHelper", "File copy exception: " + ex.ToString());
                    }
                }
                else
                {
                    LogMessage("FixHelper", "  OK leaving file in place");
                }

                // Now make sure our version of Helper is the COM registered version!
                LogMessage("FixHelper", "  Fixing COM Registration");
                if (VersionCode.OSBits() == VersionCode.Bitness.Bits64) // We are running on a 64bit OS
                {
                    SHGetSpecialFolderPath(IntPtr.Zero, PathShell, CSIDL_SYSTEMX86, 0);
                }
                else // We are running on a 32bit OS
                {
                    SHGetSpecialFolderPath(IntPtr.Zero, PathShell, CSIDL_SYSTEM, 0);// Get the system directory
                }
                string           RegSvr32Path = PathShell.ToString() + "\\RegSvr32.exe"; //Construct the full path to RegSvr32.exe
                string           AscomPath    = AscomDirectory + "\\" + HelperName;
                ProcessStartInfo Info         = new ProcessStartInfo();
                Info.FileName  = RegSvr32Path;               //Populate the ProcessStartInfo with the full path to RegSvr32.exe
                Info.Arguments = "/s \"" + AscomPath + "\""; // And the start parameter specifying the file to COM register

                LogMessage("FixHelper", "  RegSvr32 Path: \"" + RegSvr32Path + "\", COM Path: \"" + AscomPath + "\"");

                Process P = new Process(); // Create the process
                P.StartInfo = Info;        // Set the start info
                P.Start();                 //Start the process and wait for it to finish
                LogMessage("FixHelper", "  Started registration");
                P.WaitForExit();
                LogMessage("FixHelper", "  Finished registration, Return code: " + P.ExitCode);
                P.Dispose();
            }
            catch (Exception ex)
            {
                LogError("FixHelper", "FixHelper exception: " + ex.ToString());
            }
        }
        /// <summary>
        /// Creates a <see cref="GetBulkRequestMessage"/> with a specific <see cref="Sequence"/>.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="requestId">The request id.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="contextName">Context name.</param>
        /// <param name="nonRepeaters">The non repeaters.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="maxMessageSize">Size of the max message.</param>
        /// <param name="report">The report.</param>
        public GetBulkRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, OctetString contextName, int nonRepeaters, int maxRepetitions, List <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
        {
            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (contextName == null)
            {
                throw new ArgumentNullException(nameof(contextName));
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("Only v3 is supported.", nameof(version));
            }

            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            if (privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            if (nonRepeaters > variables.Count)
            {
                throw new ArgumentException("nonRepeaters should not be greater than variable count.", nameof(nonRepeaters));
            }

            if (maxRepetitions < 1)
            {
                throw new ArgumentException("maxRepetitions should be greater than 0.", nameof(maxRepetitions));
            }

            Version = version;
            Privacy = privacy;

            // TODO: define more constants.
            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
            var parameters             = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                parameters.EngineId,
                parameters.EngineBoots,
                parameters.EngineTime,
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new GetBulkRequestPdu(
                requestId,
                nonRepeaters,
                maxRepetitions,
                variables);
            var scope           = report.Scope;
            var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;

            Scope = new Scope(contextEngineId, contextName, pdu);

            Privacy.ComputeHash(Version, Header, Parameters, Scope);
            _bytes = this.PackMessage(null).ToBytes();
        }
 public GetBulkRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, int nonRepeaters, int maxRepetitions, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, nonRepeaters, maxRepetitions, variables, privacy, 0xFFE3, report)
 {
 }
 private bool IsValidForPeriod(Period period, VersionCode profileVersion)
 {
     return(period.YearUInt() == profileVersion);
 }
        internal GetBulkRequestMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }
            
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }
            
            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            Version = version;
            Header = header;
            Parameters = parameters;
            Scope = scope;
            Privacy = privacy;

            _bytes = this.PackMessage(length).ToBytes();
        }
示例#46
0
 public VersionCode CreateVersionCode(VersionCode versionCode)
 {
     return(versionCode);
 }
示例#47
0
 protected VersionName CreateVersionName(VersionCode versionCode)
 {
     return(versionCode.ToString());
 }
示例#48
0
 /// <summary>
 /// Gets the data.
 /// </summary>
 /// <param name="version">The version.</param>
 /// <returns></returns>
 public ISnmpData GetData(VersionCode version)
 {
     return(version == VersionCode.V3 ? ToSequence() : null);
 }
示例#49
0
        static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;

            OptionSet p = new OptionSet()
                          .Add("c:", "-c for community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                        {
                                                                                                            community = v;
                                                                                                        }
                               })
                          .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "-a for authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "-x for privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "-X for privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "-u for security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "-h, -?, -help for help.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "-V to display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("t:", "-t for timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "-r for retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "-v for SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            List <string> extra = p.Parse(args);

            if (showHelp)
            {
                ShowHelp();
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            if (extra.Count < 2)
            {
                ShowHelp();
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + (extra.Count - 1));
                return;
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                    case 'i':
                        data = new Integer32(int.Parse(extra[i + 2]));
                        break;

                    case 'u':
                        data = new Gauge32(uint.Parse(extra[i + 2]));
                        break;

                    case 't':
                        data = new TimeTicks(uint.Parse(extra[i + 2]));
                        break;

                    case 'a':
                        data = new IP(IPAddress.Parse(extra[i + 2]));
                        break;

                    case 'o':
                        data = new ObjectIdentifier(extra[i + 2]);
                        break;

                    case 'x':
                        data = new OctetString(ByteTool.Convert(extra[i + 2]));
                        break;

                    case 's':
                        data = new OctetString(extra[i + 2]);
                        break;

                    case 'd':
                        data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                        break;

                    case 'n':
                        data = new Null();
                        break;

                    default:
                        Console.WriteLine("unknown type string: " + type[0]);
                        return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                             Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.NextDiscovery;
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage response = request.GetResponse(timeout, receiver);
                if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              response);
                }

                foreach (Variable v in response.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
示例#50
0
        static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyVersionAttribute>().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                var addresses = Dns.GetHostAddressesAsync(extra[0]);
                addresses.Wait();
                foreach (IPAddress address in
                         addresses.Result.Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                    case 'i':
                        data = new Integer32(int.Parse(extra[i + 2]));
                        break;

                    case 'u':
                        data = new Gauge32(uint.Parse(extra[i + 2]));
                        break;

                    case 't':
                        data = new TimeTicks(uint.Parse(extra[i + 2]));
                        break;

                    case 'a':
                        data = new IP(IPAddress.Parse(extra[i + 2]).GetAddressBytes());
                        break;

                    case 'o':
                        data = new ObjectIdentifier(extra[i + 2]);
                        break;

                    case 'x':
                        data = new OctetString(ByteTool.Convert(extra[i + 2]));
                        break;

                    case 's':
                        data = new OctetString(extra[i + 2]);
                        break;

                    case 'd':
                        data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                        break;

                    case 'n':
                        data = new Null();
                        break;

                    default:
                        Console.WriteLine("unknown type string: " + type[0]);
                        return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                             Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
#if NET452
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
#else
                    Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                    return;
#endif
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.SetRequestPdu);
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);
                ISnmpMessage      reply   = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine("Request message bytes:");
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                    Console.WriteLine("Response message bytes:");
                    Console.WriteLine(ByteTool.Convert(reply.ToBytes()));
                }

                if (reply is ReportMessage)
                {
                    if (reply.Pdu().Variables.Count == 0)
                    {
                        Console.WriteLine("wrong report message received");
                        return;
                    }

                    var id = reply.Pdu().Variables[0].Id;
                    if (id != Messenger.NotInTimeWindow)
                    {
                        var error = id.GetErrorMessage();
                        Console.WriteLine(error);
                        return;
                    }

                    // according to RFC 3414, send a second request to sync time.
                    request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, reply);
                    reply   = request.GetResponse(timeout, receiver);
                }
                else if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              reply);
                }

                foreach (Variable v in reply.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
示例#51
0
        internal static Sequence PackMessage(byte[] length, VersionCode version, ISegment header, ISegment parameters, ISnmpData data)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var items = new[] 
            {
                new Integer32((int)version),
                header.GetData(version),
                parameters.GetData(version),
                data
            };
            return new Sequence(length, items);
        }
示例#52
0
 public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, enterprise, time, variables, privacy, 0xFFE3, report)
 {
 }
示例#53
0
        private static bool HasNext(VersionCode version, IPEndPoint endpoint, OctetString community, Variable seed, int timeout, out Variable next)
        {
            if (seed == null)
            {
                throw new ArgumentNullException("seed");
            }

            var variables = new List<Variable> { new Variable(seed.Id) };
            var message = new GetNextRequestMessage(
                RequestCounter.NextId,
                version,
                community,
                variables);

            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            var errorFound = pdu.ErrorStatus.ToErrorCode() == ErrorCode.NoSuchName;
            next = errorFound ? null : pdu.Variables[0];
            return !errorFound;
        }
示例#54
0
        public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
        {
            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }

            if (report == null)
            {
                throw new ArgumentNullException("report");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            Version    = version;
            Privacy    = privacy;
            Enterprise = enterprise;
            TimeStamp  = time;

            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
            var parameters             = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                parameters.EngineId,
                parameters.EngineBoots,
                parameters.EngineTime,
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new InformRequestPdu(
                requestId,
                enterprise,
                time,
                variables);
            var scope           = report.Scope;
            var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;

            Scope = new Scope(contextEngineId, scope.ContextName, pdu);

            authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = this.PackMessage(null).ToBytes();
        }
示例#55
0
        public static void SendTrapV2(int requestId, VersionCode version, EndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList<Variable> variables)
        {
            if (version != VersionCode.V2)
            {
                throw new ArgumentException("Only SNMP v2c is supported", "version");
            }

            var message = new TrapV2Message(requestId, version, community, enterprise, timestamp, variables);
            message.Send(receiver);
        }
 private static VersionCode ParseVersionCode(string versionText)
 {
     if (string.IsNullOrEmpty(versionText))
     {
         throw new ArgumentNullException("versionText");
     }
     
     char[] delimiter = {'.'};
     string[] words = versionText.Split(delimiter);
     if (words.Length != 4)
     {
         throw new Exception("Parsing AWS Unity SDK version code fail.");
     }
     VersionCode versionCode = new VersionCode(words[0], words[1], words[2], words[3]);
     return versionCode;
 }
示例#57
0
        public static Variable[,] GetTable(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, int timeout, int maxRepetitions, IObjectRegistry registry)
        {
            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var canContinue = registry == null || registry.ValidateTable(table);
            if (!canContinue)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "not a table OID: {0}", table));
            }

            IList<Variable> list = new List<Variable>();
            var rows = version == VersionCode.V1 ? Walk(version, endpoint, community, table, list, timeout, WalkMode.WithinSubtree) : BulkWalk(version, endpoint, community, table, list, timeout, maxRepetitions, WalkMode.WithinSubtree, null, null);

            if (rows == 0)
            {
                return new Variable[0, 0];
            }

            var cols = list.Count / rows;
            var k = 0;
            var result = new Variable[rows, cols];

            for (var j = 0; j < cols; j++)
            {
                for (var i = 0; i < rows; i++)
                {
                    result[i, j] = list[k];
                    k++;
                }
            }

            return result;
        }
 public GetNextRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList <Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, variables, privacy, 0xFFE3, report)
 {
 }
示例#59
0
        SNMPPrinterColorStateModel SNMPGetColor(VersionCode version, IPEndPoint ipEndPoint, OctetString community, int timeout)
        {
            /*
             *     [string]$ColorName=Invoke-SNMPget $IPAddress ".1.3.6.1.2.1.43.12.1.1.4.1.1"
             *      [int]$TonerRemaining=Invoke-SNMPget $IPAddress ".1.3.6.1.2.1.43.11.1.1.9.1.1"
             *      [int]$TonerMaxLevel=Invoke-SNMPget $IPAddress ".1.3.6.1.2.1.43.11.1.1.8.1.1"
             *
             */

            SNMPPrinterColorStateModel snmpPrinterColorState = new SNMPPrinterColorStateModel();

            List <Variable> variable = new List <Variable>();

            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.12.1.1.4.1.1"))); // Color Name - Black
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.9.1.1"))); //is the maximum of black toner remaining
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.8.1.1"))); //is the maximum black toner level
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.12.1.1.4.1.2"))); //Color Name - Cyan
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.9.1.2"))); //is the maximum of cyan toner remaining
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.8.1.2"))); //is the maximum cyan toner level
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.12.1.1.4.1.3"))); //Color Name - Magenta
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.9.1.3"))); //is the maximum of magenta toner remaining
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.8.1.3"))); // is the maximum magenta toner level
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.12.1.1.4.1.4"))); //Color Name - Yellow
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.9.1.4"))); //is the maximum of yellow toner remaining
            variable.Add(new Variable(new ObjectIdentifier(".1.3.6.1.2.1.43.11.1.1.8.1.4"))); // is the maximum yellow toner level

            try
            {
                var result = Messenger.Get(version,
                                           ipEndPoint,
                                           community,
                                           variable,
                                           timeout);

                if (result != null)
                {
#if DEBUG
                    foreach (Variable res in result)
                    {
                        Console.WriteLine(res);
                    }
#endif

                    snmpPrinterColorState.ColorNameBlack      = result[0].Data.ToString();
                    snmpPrinterColorState.TonerRemainingBlack = CheckVariableDataForInt(result[1].Data);
                    snmpPrinterColorState.MaxLevelBlack       = CheckVariableDataForInt(result[2].Data);

                    snmpPrinterColorState.ColorNameCyan      = result[3].Data.ToString();
                    snmpPrinterColorState.TonerRemainingCyan = CheckVariableDataForInt(result[4].Data);
                    snmpPrinterColorState.MaxLevelCyan       = CheckVariableDataForInt(result[5].Data);

                    snmpPrinterColorState.ColorNameMagenta      = result[6].Data.ToString();
                    snmpPrinterColorState.TonerRemainingMagenta = CheckVariableDataForInt(result[7].Data);
                    snmpPrinterColorState.MaxLevelMagenta       = CheckVariableDataForInt(result[8].Data);

                    snmpPrinterColorState.ColorNameYellow      = result[9].Data.ToString();
                    snmpPrinterColorState.TonerRemainingYellow = CheckVariableDataForInt(result[10].Data);
                    snmpPrinterColorState.MaxLevelYellow       = CheckVariableDataForInt(result[11].Data);
                }
            }
            catch
            {
#if DEBUG
                Console.WriteLine("Error result Color");
#endif
            }

            return(snmpPrinterColorState);
        }
示例#60
0
    private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
    {
        foreach (string assetPath in importedAssets)
        {
            string      ext                 = Path.GetExtension(assetPath);
            string      importedVersion     = null;
            string      existingVersion     = null;
            VersionCode importedVersionCode = null;
            VersionCode existingVersionCode = null;
            string      importedComponent   = null;
            string      existingComponent   = null;

            // Only operate on txt files
            if (!string.IsNullOrEmpty(ext) && ext.ToLower() == ".txt" && assetPath.Contains(SDK_VERSION_PREFIX))
            {
                try
                {
                    // read imported version
                    System.IO.StreamReader reader = new System.IO.StreamReader(assetPath);
                    importedVersion = reader.ReadToEnd();
                    reader.Close();
                    // parse version code
                    importedVersionCode = ParseVersionCode(importedVersion);
                    // get component name
                    importedComponent = GetComponentName(assetPath);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }

                // find out all Resource folder and search for aws-unity-sdk version file
                List <string> resourceDirs = GetAllResourcesDirs();

                foreach (string dir in resourceDirs)
                {
                    string [] fileEntries = Directory.GetFiles(dir);
                    foreach (string fileName in fileEntries)
                    {
                        ext = Path.GetExtension(fileName);
                        if (!string.IsNullOrEmpty(ext) && ext.ToLower() == ".txt" && fileName.Contains(SDK_VERSION_PREFIX))
                        {
                            try
                            {
                                // get version string
                                System.IO.StreamReader reader = new System.IO.StreamReader(fileName);
                                existingVersion = reader.ReadToEnd();
                                reader.Close();

                                // parse version code
                                existingVersionCode = ParseVersionCode(existingVersion);

                                // get component name
                                existingComponent = GetComponentName(fileName);
                            }
                            catch (Exception e)
                            {
                                Debug.LogException(e);
                            }


                            // check compatibility
                            if (existingVersionCode.W != importedVersionCode.W || existingVersionCode.X != importedVersionCode.X)
                            {
                                EditorUtility.DisplayDialog("Warning",
                                                            "The existing " + existingComponent + " (" + "version " + existingVersion + ") may not be compatible with " + importedComponent + "(version " + importedVersion + "). To avoid any potential conflicts, please remove all AWS SDK and import the latest version. ",
                                                            "OK", "");

                                break;
                            }
                        }
                    }
                }
            }
        }
    }