public void ComputeServerMasterSecret(SecurityParameters sparams, byte[] raw, int offset, int length) { byte[] pubKey = new byte[raw[offset]]; Buffer.BlockCopy (raw, offset + 1, pubKey, 0, pubKey.Length); byte[] premaster = _ecdh.PerformKeyAgreement (pubKey, 48); sparams.SetupMasterSecret (premaster); }
/// <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; }
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); }
public int CreateServerKeyExchangeSign(SecurityParameters sparams, byte[] params_buffer, int params_offset, int params_length, byte[] sign_buffer, int sign_offset) { byte[] hash; using (SHA1Managed sha1 = new SHA1Managed ()) { sha1.Initialize (); sha1.TransformBlock (sparams.ClientRandom, 0, sparams.ClientRandom.Length, sparams.ClientRandom, 0); sha1.TransformBlock (sparams.ServerRandom, 0, sparams.ServerRandom.Length, sparams.ServerRandom, 0); sha1.TransformBlock (params_buffer, params_offset, params_length, params_buffer, params_offset); sha1.TransformFinalBlock (Utility.EmptyByteArray, 0, 0); hash = sha1.Hash; } // 署名 byte[] sign = _ecdsa.SignHash (hash); // DER形式に変換 // TODO: 400bit以上の署名サイズに対応させる byte der_len = (byte)(sign.Length + 6); byte int_len = (byte)(sign.Length >> 1); sign_buffer[sign_offset + 0] = 0x30; sign_buffer[sign_offset + 1] = (byte)(der_len - 2); sign_buffer[sign_offset + 2] = 0x02; sign_buffer[sign_offset + 3] = int_len; Buffer.BlockCopy (sign, 0, sign_buffer, sign_offset + 4, int_len); sign_offset += int_len + 4; sign_buffer[sign_offset + 0] = 0x02; sign_buffer[sign_offset + 1] = int_len; Buffer.BlockCopy (sign, int_len, sign_buffer, sign_offset + 2, int_len); return der_len; }
/// <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(); }
/// <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(); }
protected HandshakeSession(SecurityParameters securityParameters) { string path = System.Reflection.Assembly.GetAssembly(typeof(HandshakeSession)).Location; string directory = Path.GetDirectoryName(path); _pluginManager = new CipherSuitePluginManager(directory); _state = HandshakeState.Initial; _minVersion = securityParameters.MinimumVersion; _maxVersion = securityParameters.MaximumVersion; _supportedCipherSuites = securityParameters.CipherSuiteIDs.ToArray(); _supportedCompressions = securityParameters.CompressionIDs.ToArray(); _availableCertificates = new List<X509CertificateCollection>(securityParameters.AvailableCertificates); _availablePrivateKeys = new List<CertificatePrivateKey>(securityParameters.AvailablePrivateKeys); _clientCertificates = new X509CertificateCollection(); _serverCertificates = new X509CertificateCollection(); // Initialize the default ClientHello version, to // be as compatible as possible based on maxVersion if (_maxVersion == ProtocolVersion.SSL3_0) { _version = ProtocolVersion.SSL3_0; } else if (_maxVersion.IsUsingDatagrams) { _version = ProtocolVersion.DTLS1_0; } else { _version = ProtocolVersion.TLS1_0; } _cipherSuite = new CipherSuite(_version); }
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(); }
protected HandshakeSession(SecurityParameters securityParameters, ILogger logger) { this.logger = logger; _pluginManager = new CipherSuitePluginManager(this.logger); _state = HandshakeState.Initial; _minVersion = securityParameters.MinimumVersion; _maxVersion = securityParameters.MaximumVersion; _supportedCipherSuites = securityParameters.CipherSuiteIDs.ToArray(); _supportedCompressions = securityParameters.CompressionIDs.ToArray(); _availableCertificates = new List<X509CertificateCollection>(securityParameters.AvailableCertificates); _availablePrivateKeys = new List<CertificatePrivateKey>(securityParameters.AvailablePrivateKeys); _clientCertificates = new X509CertificateCollection(); _serverCertificates = new X509CertificateCollection(); // Initialize the default ClientHello version, to // be as compatible as possible based on maxVersion _version = _minVersion; _cipherSuite = new CipherSuite(_version); }
/// <summary> /// Initializes a new instance of the <see cref="MalformedMessage"/> class. /// </summary> /// <param name="messageId">The message id.</param> /// <param name="user">The user.</param> public MalformedMessage(int messageId, OctetString user) { if (user == null) { throw new ArgumentNullException("user"); } MessageId = messageId; Parameters = new SecurityParameters(null, null, null, user, null, null); Pdu = MalformedPdu.Instance; }
public void ComputeServerMasterSecret(SecurityParameters sparams, byte[] raw, int offset, int length) { ushort encryptedLength = BitConverterBE.ReadUInt16 (raw, offset); if (encryptedLength > length - 2) { encryptedLength = (ushort)length; } else { offset += 2; } byte[] encrypted = new byte[encryptedLength]; Buffer.BlockCopy (raw, offset, encrypted, 0, encryptedLength); byte[] decrypted = _rsa.Decrypt (encrypted, false); sparams.SetupMasterSecret (decrypted); }
public void TestEncrypt2() { byte[] expected = ByteTool.Convert("04 30 4B 4F 10 3B 73 E1 E4 BD 91 32 1B CB 41" + "1B A1 C1 D1 1D 2D B7 84 16 CA 41 BF B3 62 83 C4" + "29 C5 A4 BC 32 DA 2E C7 65 A5 3D 71 06 3C 5B 56" + "FB 04 A4"); OctetString engineId = new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")); DESPrivacyProvider priv = new DESPrivacyProvider(new OctetString("passtest"), new MD5AuthenticationProvider(new OctetString("testpass"))); Scope scope = new Scope(engineId, OctetString.Empty, new GetRequestPdu(0x3A25, ErrorCode.NoError, 0, new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })); SecurityParameters parameters = new SecurityParameters(engineId, new Integer32(0x14), new Integer32(0x35), new OctetString("lexmark"), new OctetString(new byte[12]), new OctetString(ByteTool.Convert("00 00 00 01 44 2C A3 B5"))); ISnmpData data = priv.Encrypt(scope.GetData(VersionCode.V3), parameters); Assert.AreEqual(SnmpType.OctetString, data.TypeCode); Assert.AreEqual(expected, ByteTool.ToBytes(data)); }
internal static ISnmpData GetScopeData(this IPrivacyProvider privacy, Header header, SecurityParameters parameters, ISnmpData rawScopeData) { if (privacy == null) { throw new ArgumentNullException("privacy"); } if (header == null) { throw new ArgumentNullException("header"); } return Levels.Privacy == (header.SecurityLevel & Levels.Privacy) ? privacy.Encrypt(rawScopeData, parameters) : rawScopeData; }
/// <summary> /// Encrypts the specified scope. /// </summary> /// <param name="data">The scope data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Encrypt(ISnmpData data, SecurityParameters parameters) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (data == null) { throw new ArgumentNullException("data"); } if (data.TypeCode == SnmpType.Sequence || data is ISnmpPdu) { return data; } throw new ArgumentException("unencrypted data is expected.", "data"); }
/// <summary> /// Decrypts the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Decrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException("data"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (data.TypeCode != SnmpType.Sequence) { var newException = new DecryptionException("Default decryption failed"); throw newException; } return data; }
/// <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 = new SecurityParameters(null, null, null, community, null, null); GetBulkRequestPdu pdu = new GetBulkRequestPdu( requestId, nonRepeaters, maxRepetitions, variables); Scope = new Scope(pdu); Privacy = DefaultPrivacyProvider.DefaultPair; _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).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 ServerHandshakeSession(SecurityParameters securityParameters) : base(securityParameters) { if (securityParameters.ServerCertificateSelectionCallback != null) { _certificateSelectionCallback = securityParameters.ServerCertificateSelectionCallback; } else { _certificateSelectionCallback = new ServerCertificateSelectionCallback(DefaultCertificateSelectionCallback); } _availableCertificates = new List<X509CertificateCollection>(); _availableCertificates.AddRange(securityParameters.AvailableCertificates); _availablePrivateKeys = new List<CertificatePrivateKey>(); _availablePrivateKeys.AddRange(securityParameters.AvailablePrivateKeys); if (securityParameters.ClientCertificateTypes.Count > 0) { _certificateRequest = new HandshakeCertificateRequest(_version); _certificateRequest.CertificateTypes.AddRange(securityParameters.ClientCertificateTypes); _certificateRequest.SignatureAndHashAlgorithms.AddRange(_pluginManager.GetSupportedSignatureAndHashAlgorithms()); _certificateRequest.CertificateAuthorities.AddRange(securityParameters.ClientCertificateAuthorities); } }
public ClientHandshakeSession(SecurityParameters securityParameters) : base(securityParameters) { if (securityParameters.ServerCertificateValidationCallback != null) { _certificateValidationCallback = securityParameters.ServerCertificateValidationCallback; } else { _certificateValidationCallback = new ServerCertificateValidationCallback(DefaultCertificateValidationCallback); } if (securityParameters.ClientCertificateSelectionCallback != null) { _certificateSelectionCallback = securityParameters.ClientCertificateSelectionCallback; } else { _certificateSelectionCallback = new ClientCertificateSelectionCallback(DefaultCertificateSelectionCallback); } HandshakeClientHello clientHello = new HandshakeClientHello(_maxVersion); clientHello.CipherSuites.AddRange(_supportedCipherSuites); clientHello.CompressionMethods.AddRange(_supportedCompressions); clientHello.Extensions.Add(new HelloSignatureAlgorithmsExtension(_pluginManager.GetSupportedSignatureAndHashAlgorithms())); OutputMessage(clientHello); _connectionState.ClientRandom = clientHello.Random.GetBytes(); }
public InformRequestMessage(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList <Variable> variables) { if (variables == null) { throw new ArgumentNullException(nameof(variables)); } if (enterprise == null) { throw new ArgumentNullException(nameof(enterprise)); } if (community == null) { throw new ArgumentNullException(nameof(community)); } if (version == VersionCode.V3) { throw new ArgumentException("Only v1 and v2c are supported.", nameof(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(); }
/// <summary> /// Creates a <see cref="TrapV1Message"/> instance with a message body. /// </summary> /// <param name="body">Message body</param> public TrapV1Message(Sequence body) { if (body == null) { throw new ArgumentNullException("body"); } if (body.Length != 3) { throw new ArgumentException("wrong message body"); } Community = (OctetString)body[1]; Version = (VersionCode)((Integer32)body[0]).ToInt32(); // IMPORTANT: comment this check out if you need to support if (Version != VersionCode.V1) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", Version), "body"); } _pdu = (ISnmpPdu)body[2]; if (_pdu.TypeCode != SnmpType.TrapV1Pdu) { throw new ArgumentException("wrong message type"); } var trapPdu = (TrapV1Pdu)_pdu; Enterprise = trapPdu.Enterprise; AgentAddress = trapPdu.AgentAddress.ToIPAddress(); Generic = trapPdu.Generic; Specific = trapPdu.Specific; TimeStamp = trapPdu.TimeStamp.ToUInt32(); Parameters = SecurityParameters.Create(Community); _bytes = SnmpMessageExtension.PackMessage(Version, Community, _pdu).ToBytes(); }
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 = new SecurityParameters(null, null, null, community, null, null); InformRequestPdu pdu = new InformRequestPdu( requestId, enterprise, time, variables); Scope = new Scope(pdu); Privacy = DefaultPrivacyProvider.DefaultPair; _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes(); }
public void TestEncrypt2() { byte[] expected = ByteTool.Convert( "04 30 9D 13 04 9C 7E D9 84 8B 33 C3 26 5C 1F 91 30 27 D3 56 B0 FD 81 36 50 3A EF 80 1C B9 25 D6 38 84 A7 07 45 FE E8 D7 01 83 A1 CE 04 79 9D 5F 9E 2F"); OctetString engineId = new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")); IPrivacyProvider priv; if (AESPrivacyProviderBase.IsSupported) { priv = new AESPrivacyProvider(new OctetString("passtest"), new MD5AuthenticationProvider(new OctetString("testpass"))); } else { priv = new BouncyCastle.BouncyCastleAESPrivacyProvider(new OctetString("passtest"), new MD5AuthenticationProvider(new OctetString("testpass"))); } Scope scope = new Scope(engineId, OctetString.Empty, new GetRequestPdu(0x3A25, new List <Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })); SecurityParameters parameters = new SecurityParameters(engineId, new Integer32(0x14), new Integer32(0x35), new OctetString("lexmark"), new OctetString(new byte[12]), new OctetString(ByteTool.Convert("00 00 00 01 44 2C A3 B5"))); var original = scope.GetData(VersionCode.V3); ISnmpData data = priv.Encrypt(original, parameters); Assert.Equal(SnmpType.OctetString, data.TypeCode); Assert.Equal(ByteTool.Convert(expected), ByteTool.Convert(data.ToBytes())); ISnmpData decrypted = priv.Decrypt(data, parameters); Assert.Equal(ByteTool.Convert(original.ToBytes()), ByteTool.Convert(decrypted.ToBytes())); }
public override byte[] GenerateServerKeyExchange() { if (mDHParameters == null) { throw new TlsFatalAlert(80); } DigestInputBuffer digestInputBuffer = new DigestInputBuffer(); mDHAgreePrivateKey = TlsDHUtilities.GenerateEphemeralServerKeyExchange(mContext.SecureRandom, mDHParameters, digestInputBuffer); SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(mContext, mServerCredentials); IDigest digest = TlsUtilities.CreateHash(signatureAndHashAlgorithm); SecurityParameters securityParameters = mContext.SecurityParameters; digest.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length); digest.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length); digestInputBuffer.UpdateDigest(digest); byte[] hash = DigestUtilities.DoFinal(digest); byte[] signature = mServerCredentials.GenerateCertificateSignature(hash); DigitallySigned digitallySigned = new DigitallySigned(signatureAndHashAlgorithm, signature); digitallySigned.Encode(digestInputBuffer); return(digestInputBuffer.ToArray()); }
public void TestDecrypt2() { byte[] encrypted = ByteTool.Convert("04 38 A4 F9 78 15 2B 14 45 F7 4F C5 B2 1C 82 72 9A 0B D9 EE C1 17 3E E1 26 0D 8B D4 7B 0F D7 35 06 1B E2 14 0D 4A 9B CA BF EF 18 6B 53 B9 FA 70 95 D0 15 38 C5 77 96 85 61 40"); var privacy = new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))); var parameters = new SecurityParameters( new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")), Integer32.Zero, Integer32.Zero, new OctetString("lextm"), OctetString.Empty, new OctetString(ByteTool.Convert("0000000069D39B2A"))); var data = privacy.Decrypt(DataFactory.CreateSnmpData(encrypted), parameters); Assert.AreEqual(SnmpType.Sequence, data.TypeCode); byte[] net = ByteTool.Convert( "04 38 A4 F9 78 15 2B 14 45 F7 4F C5 B2 1C 82 72 9A 0B D9 EE C1 17 3E E1 26 0D 8B D4 7B 0F D7 35 06 1B E2 14 0D 4A 9B CA BF EF 18 6B 53 B9 FA 70 95 D0 5D AF 04 5A 68 B5 DA 73"); var netData = privacy.Decrypt(DataFactory.CreateSnmpData(net), parameters); Assert.AreEqual(SnmpType.Sequence, netData.TypeCode); Assert.AreEqual(ByteTool.Convert(netData.ToBytes()), ByteTool.Convert(data.ToBytes())); }
protected HandshakeSession(SecurityParameters securityParameters) { _pluginManager = new CipherSuitePluginManager(); _state = HandshakeState.Initial; _minVersion = securityParameters.MinimumVersion; _maxVersion = securityParameters.MaximumVersion; _supportedCipherSuites = securityParameters.CipherSuiteIDs.ToArray(); _supportedCompressions = securityParameters.CompressionIDs.ToArray(); _availableCertificates = new List <X509CertificateCollection>(securityParameters.AvailableCertificates); _availablePrivateKeys = new List <CertificatePrivateKey>(securityParameters.AvailablePrivateKeys); _clientCertificates = new X509CertificateCollection(); _serverCertificates = new X509CertificateCollection(); // Initialize the default ClientHello version, to // be as compatible as possible based on maxVersion _version = _minVersion; _cipherSuite = new CipherSuite(_version); }
/// <summary> /// Authenticates the request. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public bool AuthenticateRequest(ISnmpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ISnmpMessage request = context.Request; if (request.Version != Version) { return(false); } SecurityParameters parameters = request.Parameters; if (request.Pdu().TypeCode == SnmpType.SetRequestPdu) { return(parameters.UserName == _set); } return(parameters.UserName == _get); }
public Tuple <AuthenticationResult, User> AddUser(string name, string family, string username, string password, string email, DateTime birthday) { User _user = new User(); _user = _dbContext.Users.FirstOrDefault(user => user.UserName == username); if (_user != null) { return(new Tuple <AuthenticationResult, User>(new AuthenticationResult(AuthenticationResultCode.ClientConnectivityError), null)); } _user = new User(); _user.Name = name; _user.FamilyName = family; _user.UserName = username; _user.Password = SecurityParameters.MD5Encryption(password); _user.Email = email; _user.BirthDate = birthday; _dbContext.Users.Add(_user); _dbContext.SaveChanges(); return(new Tuple <AuthenticationResult, User>(new AuthenticationResult(AuthenticationResultCode.AuthenticationSuccess), _user)); }
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 = SecurityParameters.Create(community); var pdu = new TrapV2Pdu( 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> /// 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> /// Encrypts the specified scope. /// </summary> /// <param name="data">The scope data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Encrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data.TypeCode != SnmpType.Sequence && !(data is ISnmpPdu)) { throw new ArgumentException("Invalid data type.", nameof(data)); } var pkey = PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); var bytes = data.ToBytes(); var reminder = bytes.Length % 8; var count = reminder == 0 ? 0 : 8 - reminder; using (var stream = new MemoryStream()) { stream.Write(bytes, 0, bytes.Length); for (var i = 0; i < count; i++) { stream.WriteByte(1); } bytes = stream.ToArray(); } var encrypted = Encrypt(bytes, pkey, parameters.EngineBoots.ToInt32(), parameters.EngineTime.ToInt32(), parameters.PrivacyParameters.GetRaw()); return(new OctetString(encrypted)); }
/// <summary> /// Creates a <see cref="TrapV1Message"/> instance with a message body. /// </summary> /// <param name="body">Message body</param> public TrapV1Message(Sequence body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } if (body.Length != 3) { throw new ArgumentException("Invalid message body.", nameof(body)); } Community = (OctetString)body[1]; Version = (VersionCode)((Integer32)body[0]).ToInt32(); // IMPORTANT: comment this check out if you need to support if (Version != VersionCode.V1) { throw new ArgumentException($"TRAP v1 is not supported in this SNMP version: {Version}.", nameof(body)); } _pdu = (ISnmpPdu)body[2]; if (_pdu.TypeCode != SnmpType.TrapV1Pdu) { throw new ArgumentException("Invalid message type.", nameof(body)); } TrapV1Pdu trapPdu = (TrapV1Pdu)_pdu; Enterprise = trapPdu.Enterprise; AgentAddress = new IPAddress(trapPdu.AgentAddress.GetRaw()); Generic = trapPdu.Generic; Specific = trapPdu.Specific; TimeStamp = trapPdu.TimeStamp.ToUInt32(); Parameters = SecurityParameters.Create(Community); _container = body; }
public override void ProcessServerKeyExchange(Stream input) { SecurityParameters securityParameters = mContext.SecurityParameters; SignerInputBuffer buf = new SignerInputBuffer(); Stream teeIn = new TeeInputStream(input, buf); ServerDHParams dhParams = ServerDHParams.Parse(teeIn); DigitallySigned signed_params = ParseSignature(input); mSignatureAndHashAlgorithm = signed_params.Algorithm; ISigner signer = InitVerifyer(mTlsSigner, signed_params.Algorithm, securityParameters); buf.UpdateSigner(signer); if (!signer.VerifySignature(signed_params.Signature)) { throw new TlsFatalAlert(AlertDescription.decrypt_error); } this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey(dhParams.PublicKey); this.mDHParameters = ValidateDHParameters(mDHAgreePublicKey.Parameters); }
/// <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(); }
/// <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); }
public virtual byte[] ExportKeyingMaterial(string asciiLabel, byte[] context_value, int length) { if (context_value != null && !TlsUtilities.IsValidUint16(context_value.Length)) { throw new ArgumentException("must have length less than 2^16 (or be null)", "context_value"); } SecurityParameters securityParameters = SecurityParameters; byte[] clientRandom = securityParameters.ClientRandom; byte[] serverRandom = securityParameters.ServerRandom; int num = clientRandom.Length + serverRandom.Length; if (context_value != null) { num += 2 + context_value.Length; } byte[] array = new byte[num]; int num2 = 0; Array.Copy(clientRandom, 0, array, num2, clientRandom.Length); num2 += clientRandom.Length; Array.Copy(serverRandom, 0, array, num2, serverRandom.Length); num2 += serverRandom.Length; if (context_value != null) { TlsUtilities.WriteUint16(context_value.Length, array, num2); num2 += 2; Array.Copy(context_value, 0, array, num2, context_value.Length); num2 += context_value.Length; } if (num2 != num) { throw new InvalidOperationException("error in calculation of seed for export"); } return(TlsUtilities.PRF(this, securityParameters.MasterSecret, asciiLabel, array, length)); }
/// <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); }
public override byte[] GenerateServerKeyExchange() { mSrpServer.Init(mSrpGroup, mSrpVerifier, TlsUtilities.CreateHash(2), mContext.SecureRandom); BigInteger b = mSrpServer.GenerateServerCredentials(); ServerSrpParams serverSrpParams = new ServerSrpParams(mSrpGroup.N, mSrpGroup.G, mSrpSalt, b); DigestInputBuffer digestInputBuffer = new DigestInputBuffer(); serverSrpParams.Encode(digestInputBuffer); if (mServerCredentials != null) { SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(mContext, mServerCredentials); IDigest digest = TlsUtilities.CreateHash(signatureAndHashAlgorithm); SecurityParameters securityParameters = mContext.SecurityParameters; digest.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length); digest.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length); digestInputBuffer.UpdateDigest(digest); byte[] array = new byte[digest.GetDigestSize()]; digest.DoFinal(array, 0); byte[] signature = mServerCredentials.GenerateCertificateSignature(array); DigitallySigned digitallySigned = new DigitallySigned(signatureAndHashAlgorithm, signature); digitallySigned.Encode(digestInputBuffer); } return(digestInputBuffer.ToArray()); }
/// <summary> /// Encrypts the specified scope. /// </summary> /// <param name="data">The scope data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Encrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException("data"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (data.TypeCode != SnmpType.Sequence && !(data is ISnmpPdu)) { throw new ArgumentException("unencrypted data is expected.", "data"); } byte[] pkey = AuthenticationProvider.PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); byte[] bytes = data.ToBytes(); int reminder = bytes.Length % 8; int count = reminder == 0 ? 0 : 8 - reminder; using (MemoryStream stream = new MemoryStream()) { stream.Write(bytes, 0, bytes.Length); for (int i = 0; i < count; i++) { stream.WriteByte(1); } bytes = stream.ToArray(); } byte[] encrypted = Encrypt(bytes, pkey, parameters.PrivacyParameters.GetRaw()); return(new OctetString(encrypted)); }
public static TlsCipher AssignCipher(byte[] preMasterSecret, bool client, Version version, HandshakeInfo handshakeInfo) { int encryptionAlgorithm = GetEncryptionAlgorithm(handshakeInfo.CipherSuite); int macAlgorithm = GetMACAlgorithm(handshakeInfo.CipherSuite); TlsContext context = new DTLSContext(client, version, handshakeInfo); SecurityParameters securityParameters = context.SecurityParameters; byte[] seed = Concat(securityParameters.ClientRandom, securityParameters.ServerRandom); string asciiLabel = ExporterLabel.master_secret; handshakeInfo.MasterSecret = TlsUtilities.PRF(context, preMasterSecret, asciiLabel, seed, 48); //session.Handshake.MasterSecret = TlsUtilities.PRF_legacy(preMasterSecret, asciiLabel, seed, 48); #if DEBUG Console.Write($"MasterSecret: {WriteToString(handshakeInfo.MasterSecret)}"); #endif seed = Concat(securityParameters.ServerRandom, securityParameters.ClientRandom); byte[] key_block = TlsUtilities.PRF(context, handshakeInfo.MasterSecret, ExporterLabel.key_expansion, seed, 96); //byte[] key_block = TlsUtilities.PRF_legacy(session.Handshake.MasterSecret, ExporterLabel.key_expansion, seed, 96); #if DEBUG Console.Write($"Key block: {WriteToString(key_block)}"); #endif return(CipherFactory.CreateCipher(context, encryptionAlgorithm, macAlgorithm)); }
/// <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> /// 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 bytes.</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(nameof(header)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (privacy == null) { throw new ArgumentNullException(nameof(privacy)); } var key = PasswordToKey(_password, parameters.EngineId.GetRaw()); var sha224 = new HMac(new Sha224Digest()); { sha224.Init(new KeyParameter(key)); var message = ByteTool.PackMessage(length, version, header, parameters, data).ToBytes(); var hash = new byte[sha224.GetMacSize()]; sha224.BlockUpdate(message, 0, message.Length); sha224.DoFinal(hash, 0); var result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return(new OctetString(result)); } }
/// <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; }
/// <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(); }
public void TestException() { var provider = new DESPrivacyProvider(new OctetString("longlongago"), new MD5AuthenticationProvider(new OctetString("verylonglongago"))); Assert.Throws <ArgumentNullException>(() => new DESPrivacyProvider(null, null)); Assert.Throws <ArgumentNullException>(() => new DESPrivacyProvider(OctetString.Empty, null)); Assert.Throws <ArgumentNullException>(() => provider.Encrypt(null, null)); Assert.Throws <ArgumentNullException>(() => provider.Encrypt(OctetString.Empty, null)); { var exception = Assert.Throws <ArgumentException>(() => provider.Encrypt(new Null(), SecurityParameters.Create(OctetString.Empty))); Assert.Contains("Invalid data type.", exception.Message); } Assert.Throws <ArgumentNullException>(() => provider.Decrypt(null, null)); Assert.Throws <ArgumentNullException>(() => provider.Decrypt(OctetString.Empty, null)); { var exception = Assert.Throws <ArgumentException>(() => provider.Decrypt(new Null(), SecurityParameters.Create(OctetString.Empty))); Assert.Contains("Cannot decrypt the scope data: Null.", exception.Message); } }
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.Count != 3 && body.Count != 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.Count == 3) { header = Header.Empty; parameters = new SecurityParameters(null, null, null, (OctetString)body[1], null, null); 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"); } } 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)); } }
/// <summary> /// Initializes a new instance of the <see cref="SetRequestMessage"/> class. /// </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="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 SetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report) { if (variables == null) { throw new ArgumentNullException("variables"); } if (userName == null) { throw new ArgumentNullException("userName"); } 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"); } Version = version; Privacy = privacy; 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 SetRequestPdu( requestId, 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(); }
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(); }
/// <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(); }
/// <summary> /// Encrypts the specified scope. /// </summary> /// <param name="data">The scope data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Encrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException("data"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (data.TypeCode != SnmpType.Sequence && !(data is ISnmpPdu)) { throw new ArgumentException("unencrypted data is expected.", "data"); } var pkey = AuthenticationProvider.PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); var bytes = data.ToBytes(); var reminder = bytes.Length % 8; var count = reminder == 0 ? 0 : 8 - reminder; using (var stream = new MemoryStream()) { stream.Write(bytes, 0, bytes.Length); for (var i = 0; i < count; i++) { stream.WriteByte(1); } bytes = stream.ToArray(); } var encrypted = Encrypt(bytes, pkey, parameters.PrivacyParameters.GetRaw()); return new OctetString(encrypted); }
/// <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> /// <param name="length">The length bytes.</param> /// <returns> /// Returns <c>true</c> if hash matches. Otherwise, returns <c>false</c>. /// </returns> public static bool VerifyHash(this IPrivacyProvider privacy, VersionCode version, Header header, SecurityParameters parameters, ISnmpData scopeBytes, byte[] length) { 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"); } var provider = privacy.AuthenticationProvider; if (provider is DefaultAuthenticationProvider) { return(true); } if (0 == (header.SecurityLevel & Levels.Authentication)) { return(true); } var expected = parameters.AuthenticationParameters; parameters.AuthenticationParameters = provider.CleanDigest; // clean the hash first. var newHash = provider.ComputeHash(version, header, parameters, scopeBytes, privacy, length); parameters.AuthenticationParameters = expected; // restore the hash. return(newHash == expected); }
/// <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> public static void ComputeHash(this IPrivacyProvider privacy, VersionCode version, Header header, SecurityParameters parameters, ISegment scope) { 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"); } var provider = privacy.AuthenticationProvider; 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 void ComputeServerMasterSecret(SecurityParameters sparams, byte[] raw, int offset, int length) { ushort len = BitConverterBE.ReadUInt16AndMoveOffset (raw, ref offset); byte[] premaster = _dh.PerformKeyAgreement (raw, offset, len); sparams.SetupMasterSecret (premaster); }
/// <summary> /// Decrypts the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public ISnmpData Decrypt(ISnmpData data, SecurityParameters parameters) { if (data == null) { throw new ArgumentNullException("data"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } var code = data.TypeCode; if (code != SnmpType.OctetString) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "cannot decrypt the scope data: {0}", code), "data"); } var octets = (OctetString)data; var bytes = octets.GetRaw(); var pkey = AuthenticationProvider.PasswordToKey(_phrase.GetRaw(), parameters.EngineId.GetRaw()); try { // decode encrypted packet var decrypted = Decrypt(bytes, pkey, parameters.PrivacyParameters.GetRaw()); var result = DataFactory.CreateSnmpData(decrypted); if (result.TypeCode != SnmpType.Sequence) { var newException = new DecryptionException("DES decryption failed"); newException.SetBytes(bytes); throw newException; } return result; } catch (Exception ex) { var newException = new DecryptionException("DES decryption failed", ex); newException.SetBytes(bytes); throw newException; } }
private static ISnmpMessage ParseMessage(int first, Stream stream, UserRegistry registry) { var array = DataFactory.CreateSnmpData(first, stream); if (array == null) { return(null); } if (array.TypeCode != SnmpType.Sequence) { throw new SnmpException("not an SNMP message"); } var body = (Sequence)array; if (body.Length != 3 && body.Length != 4) { throw new SnmpException("not an SNMP message"); } var 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, body[3])); } 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, body[3])); } } 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, body.GetLengthBytes())) { parameters.IsInvalid = true; } } var scopeCode = scope.Pdu.TypeCode; try { switch (scopeCode) { case SnmpType.TrapV1Pdu: return(new TrapV1Message(body)); case SnmpType.TrapV2Pdu: return(new TrapV2Message(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.GetRequestPdu: return(new GetRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.ResponsePdu: return(new ResponseMessage(version, header, parameters, scope, privacy, false, body.GetLengthBytes())); case SnmpType.SetRequestPdu: return(new SetRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.GetNextRequestPdu: return(new GetNextRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.GetBulkRequestPdu: return(new GetBulkRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.ReportPdu: return(new ReportMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); case SnmpType.InformRequestPdu: return(new InformRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes())); default: throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "unsupported pdu: {0}", scopeCode)); } } catch (Exception ex) { if (ex is SnmpException) { throw; } throw new SnmpException("message construction exception", ex); } }
/// <summary> /// Computes the hash. /// </summary> /// <param name="authen">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 authen, VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy) { if (authen == null) { throw new ArgumentNullException("authen"); } 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 (authen is DefaultAuthenticationProvider) { return; } // replace the hash. parameters.AuthenticationParameters = authen.ComputeHash(version, header, parameters, privacy.Encrypt(scope.GetData(version), parameters), privacy); }
/// <summary> /// Verifies the hash. /// </summary> /// <param name="authen">The authentication provider.</param> /// <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 <code>true</code> if hash matches. Otherwise, returns <code>false</code>. /// </returns> public static bool VerifyHash(this IAuthenticationProvider authen, VersionCode version, Header header, SecurityParameters parameters, ISnmpData scopeBytes, IPrivacyProvider privacy) { if (authen == null) { throw new ArgumentNullException("authen"); } 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"); } if (authen is DefaultAuthenticationProvider) { return(true); } var expected = parameters.AuthenticationParameters; parameters.AuthenticationParameters = authen.CleanDigest; // clean the hash first. bool result = authen.ComputeHash(version, header, parameters, scopeBytes, privacy) == expected; parameters.AuthenticationParameters = expected; // restore the hash. return(result); }
/// <summary> /// Gets the scope data. /// </summary> /// <param name="privacy">The privacy provider.</param> /// <param name="header">The header.</param> /// <param name="parameters">The parameters.</param> /// <param name="rawScopeData">The raw scope data.</param> /// <returns>ISnmpData.</returns> /// <exception cref="System.ArgumentNullException"> /// privacy /// or /// header /// </exception> public static ISnmpData GetScopeData(this IPrivacyProvider privacy, Header header, SecurityParameters parameters, ISnmpData rawScopeData) { if (privacy == null) { throw new ArgumentNullException("privacy"); } if (header == null) { throw new ArgumentNullException("header"); } return(Levels.Privacy == (header.SecurityLevel & Levels.Privacy) ? privacy.Encrypt(rawScopeData, parameters) : rawScopeData); }
/// <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"); } var key = PasswordToKey(_password, parameters.EngineId.GetRaw()); using (var md5 = new HMACMD5(key)) { var hash = md5.ComputeHash(ByteTool.PackMessage(length, version, header, parameters, data).ToBytes()); md5.Clear(); var result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return new OctetString(result); } }