Why can't I send this IP packet? - c#

I'm trying to send an IP packet using c#.
destAddress = IPAddress.Parse("192.168.0.198"),
destPort = 80;
// Create a raw socket to send this packet
rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
// Bind the socket to the interface specified
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.140"),0);
rawSocket.Bind(iep);
// Set the HeaderIncluded option since we include the IP header
rawSocket.SetSocketOption( socketLevel, SocketOptionName.HeaderIncluded, 1 );
// Send the packet!
int rc = rawSocket.SendTo(builtPacket, new IPEndPoint(destAddress, destPort));
Console.WriteLine("sent {0} bytes to {1}", rc, destAddress.ToString());
The content of builtPacket is shown below. It's an IP packet containing a TCP SYN packet (That's what I think I created anyway).
45 00 00 28 00 00 00 00 02 06 36 6E C0 A8 00 8C
C0 A8 00 C6 14 1E 00 50 00 00 00 00 00 00 00 00
05 02 FF FF E6 4F 00 00
The output is:
sent 40 bytes to 192.168.0.198
The problem is I don't see anything in the Wireshark trace. It's like the data is not getting far enough down the stack for Wireshark to see it? If I use a browser to connect to 192.168.0.198, Wireshark shows all the packets, but shows nothing when I try to send a packet using the above code and data.
My config:
I am running as admin so it's not a permissions problem.
Windows7 ( Not running in a VM)
Wireless connection only (IP config reports its IP as 192.168.0.140)
What am I doing wrong?
I'm sure Occam's Razor applies here, but I've been looking at this for hours and can't figure out what's wrong.

This question, backed up by MSDN, claims that Windows no longer (XP SP 2 through 7) allows transmission of TCP data using raw sockets.

My guess is that either Wireshark is not looking at the right network interface, or that the destination ip address somehow resolves to the local machine, in which case it will routed inside of the OS and be invisible to the 'Shark.

Related

System.TimeoutException being Thrown when Attempting to Write to Holding Registers using NModbus

I'm attempting to write a Modbus master program in C# that writes values into the holding registers of a single slave device over a RTU serial connection.
void SerialTimerTick(object sender, EventArgs e) {
_sp.WriteLine(inputText.ToString());
slaveAddress = (byte)slaveAddressNumericUpDown.Value;
startAddress = (ushort)startAddressNumericUpDown.Value;
registerAddress = (ushort)registerNumericUpDown.Value;
targetRegisterValue = (ushort)targetValueNumericUpDown.Value;
modbusMaster.WriteSingleRegister(slaveAddress, registerAddress, targetRegisterValue);
SerialTimer.Enabled = false;
sendButton.Enabled = true;
}
The problem is that when I attempt to send the write request to the slave, I get the following error:
System.TimeoutException: The operation has timed out.
which happens after the program outputs these numbers to the debug console in SharpDevelop three times, indicating three attempts:
254
120
128
34
32
25
To fix it, I've tried using break points to diagnose the problem, and it appears that NModbus is expecting some kind of ACKNOWLEDGE response from the slave in order to confirm that the data was sent correctly, only no such response is given.
When I look at my slave's communications feed, I see that something is happening on the slave's end when both the master and slave applications are running and my computer is connected to itself using two USB to Serial adapters:
Port COM 3 opened.
Port I/O buffers configured.
Port configured 256000,8,N,1
Timeouts configured (100ms/500ms)
Modem status : [CTS_][DSR_RING_]
RX: 0D 0A 0A 06 00 01
RX: 00 01 19 CA
RX: 01 06 00 01 00 01
RX: 19 CA
RX: 01 06 00 01 00 01
Instead, what I expected is for the first attempt to succeed and for the 40001 register to change its value from zero to one. I've tried changing NModbus versions, I've tried messing with the timeout and attempt settings of the IModbusMasterobject and I've also tried removing the exception entirely, which seems to be the only way I've gotten the program to work correctly, however this isn't an acceptable solution in my case.
The only thing I haven't tried so far is changing the slave application I'm using, which is currently the free PLC Simulator, which is written in C++ and not C#. This might be part of the problem, but I'm not sure.
I've only been using Modbus for a few weeks, and am working with a rather old version of the NModbus library. Any help would be much appreciated.
I haven't used NModbus, but I have written my own Modbus "stack" in C++ and C# so this answer is based more on my experience with Modbus than on how NModbus works.
There should be a response from Modbus commands EXCEPT when broadcasted (slave address 0). It should be normal operation for Modbus code to send the request and wait for a response. If the response is not received in a some specified amount of time, I would expect a timeout error.
Looking at the modbus spec; the write single register function should have an identical request and response ADU (if successful). It sounds like you are trying to write slave address 1 register 1 with a value 1. In that case, both the request response ADUs should be "01 06 00 01 00 01 19 CA" ("19 CA" is the correct CRC for this PDU). I do see what could be data from a request or response, but there seems to be something interfering:
RX: 0D 0A (NOT SURE WHAT THIS DATA IS FROM)
RX: 0A 06 00 01 00 01 19 CA (LOOKS CLOSE, BUT ADDRESS IS WRONG)
RX: 01 06 00 01 00 01 19 CA (LOOKS CORRECT)
RX: 01 06 00 01 00 01 (LOOKS CORRECT, BUT INCOMPLETE)
Just to test, try a much slower baud rate (9600) and use even parity. Some USB to Serial converters have driver parameters that can be tweaked. Do you have termination enabled on both converters (first and last devices terminated)? Is there a way to configure the NModbus response timeout?

my view in asp.net mvc crashed?

I use Visual Studio 2013 with ASP.NET MVC 5 and TFS when I run project
my PC turns off.
When I run VS again my one view that is not in TFS gives me an error, it was working fine before my PC turned off.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message:
CS1009: Unrecognized escape sequence
Source Error:
Line 51: BeginContext("~/Views/ATM/CreateExecl.cshtml", 0, 4434, true);
Line 52:
Line 53: WriteLiteral("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" +
and view in project like : -
000000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...............
000000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...............
Your file probably became corrupted due to the power outage. You'll need to rewrite your view since it sounds like you didn't yet have it checked into source code control.
In order to avoid this in the future, it's wise to have your computer on an Uninterruptible Power Supply. These are basically large batteries you plug your PC and monitor and other essential equipment into that give you some time to save your work and perform a proper shut down in the event of a power outage, or allow you to keep working through brief power outages.

Oracle.ManagedDataAccess and ORA-01017: invalid username/password; logon denied

I have a challenging situation on one of our servers. I have an ASP.NET MVC 3 application that needs to connect to an Oracle 12c database. It does so using the following connection string:
User ID=myuserid;Password=mypass;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=<IP ADDRESS>)(PORT = 1521)))(CONNECT_DATA=(SERVICE_NAME=PDB1)));
I'm also using Oracle's Oracle.ManagedDataAccess, version 4.121.1.0. Each attempt to connect results in the following error:
ORA-01017: invalid username/password; logon denied
I can connect successfully on my desktop with the above credentials. I have the same code on another server, but using an older, un-managed version of the library, and it can connect successfully with the aforementioned credentials. However, the server on which I would like my code to run fails every single time using the same credentials that enable successful connections on different servers.
On the server that fails, I can:
connect via SQLPLUS
hit the database with TNSPING
Create a System DSN to establish an ODBC connection
I have checked the TNSNAMES.ORA in all locations and they appear to be correct.
After hitting the database too many times, the account actually locked indicating that I was, indeed, hitting the database and that the database did not like the credentials presented. I checked the applications that previously connected successfully and they also failed with an error indicating that the account was locked. Unlocking the account caused those applications to connect successfully with the exception of the server with which I am having problems.
I am at my wit's end.
Does anyone have any other suggestions as to what might cause this problem?
EDIT:
I installed WireShark on my local computer and on the offending server. I captured communication between my desktop and the database as well as the offending server and the database. I found that my desktop communicated the password:
0080 35 42 31 41 43 34 30 00 01 01 01 0d 0d 41 55 54 5B1AC40......AUT
0090 48 5f 50 41 53 53 57 4f 52 44 01 40 40 43 30 36 H_PASSWORD.##C06
00a0 37 39 42 31 31 42 46 36 42 41 43 44 39 30 38 44 79B11BF6BACD908D
00b0 37 39 34 34 31 31 46 34 32 33 30 42 34 36 44 36 794411F4230B46D6
00c0 35 36 36 33 31 42 45 39 39 41 36 43 36 37 42 44 56631BE99A6C67BD
00d0 43 33 35 42 42 44 36 44 42 45 37 34 36 00 01 0d C35BBD6DBE746...
whereas the server with which I am having problems, did not (or at least that's the assumption):
0080 39 33 39 37 32 33 46 00 01 01 01 0d 0d 41 55 54 939723F......AUT
0090 48 5f 50 41 53 53 57 4f 52 44 01 40 40 00 00 00 H_PASSWORD.##...
00a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 0d ................
Does anyone know of a security/configuration setting that would prevent passwords from being transmitted even though they are present in the connection string?
Edit (20180713):
In my particular case, the issue was the FIPS setting.
For those doing research, there are several ways around this.
You can alter the registry setting located at HKLM\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled. If FIPS is enabled, the value is 1. If disabled, the value is 0. You do not need to reboot.
Most likely, the reason why you are running into this issue is that FIPS is enabled and you are using the Oracle managed data access library. A solid workaround is to use the unmanaged library. However, to use this library, you need to install the Oracle Instant Client. The client is available for download in the Oracle Data Access Components.
Upgrade your server to Oracle 12.2c. Oracle 12c versions before 12.2c still have this problem.
If you do not have FIPS enabled, the most likely you will need to investigate whether your database has the SEC_CASE_SENSITIVE_LOGON setting set to true. You will need to execute ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE; and then reset all of your passwords.
I have been struggling with this same issue for a couple of weeks and finally have a resolution. I had to disable the FIPS security policy, try setting this key:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy]
"Enabled"=dword:00000000
to zero, it worked perfectly for me
I was following your thread your blank password issue eventually pointed me here:
https://community.oracle.com/thread/2557592?start=30&tstart=0
Based on Jeff's answer (10/31/2014)...
The registry setting can be set by GPO to only allow FIPS compliant algorithms. Setting this to 0 as indicated may be a violation of some security policies and get overwritten by the GPO. This registry setting controls more than just IIS or ASP.NET.
There is another way that is specific to .NET and may work at the application level. This is much easier to justify compared to modifying the settings of the whole server.
Application specific method:
In your Web.config or App.config file, add the following setting:
<configuration> <!-- Will already be there -->
<runtime>
<enforceFIPSPolicy enabled="false"/>
</runtime>
... the rest of your .config
If I remember correctly, this must be at the beginning of your config file.
All .NET application method:
Place the setting above in the machine.config file. There will be one for each .NET version and architecture (64 bit/32 bit). There will already be a element, so put the element inside it.
I had the same issue using Entity Framework and the Oracle.ManagedDataAccess.Client, but I had some success by uppercasing my password in the configuration connection string section.
I'm programming in C # with an Oracle xe 11g database, it had never happened to me before, but the new users that I created in the DB, when I tried to connect from the C# application, I got the error: ORA-01017: invalid username / password ; logon denied, only with new users (I did a migration from xe 10g to xe 11g) where migrated users from version 10g worked correctly.
I made this change in my connection string and managed to solve the problem
before
private string cadenaCone = "User Id=AAA111;Password=BBB222;Data Source=CCC333;Connection Timeout=60;";
after
private string cadenaCone = "User Id=AAA111;Password=" + ((char)34).ToString() + "BBB222"+((char)34).ToString()+";Data Source=CCC333;Connection Timeout=60;";
I did not quite have the same scenario as this case does, but I did have very similar results. What I did to sort out the problem was, I enclosed the password in quotes like the following (VB.NET):
cnx.ConnectionString = "User ID=MYID;Password=""MyPass"" ;Data Source=MyTEST"
or use chr(34) as follows
cnx.ConnectionString = "User ID=MYID;Password="+chr(34)+"MyPass"+chr(34)+" ;Data Source=MyTEST"
I had exactly same issue. When I was connecting to database directly from SqlDeveloper, it was working fine. But my application ( built on VB6) failed to connect to Oracle and giving error "ORA-01017 Invalid ID/password.
After turning off, case sensitive login for my database ID, it resolved the issue.
I had the same problem! I didn't try changing the RegKey but I did try changing the web and machine config. This did not work.
What did solve the problem was changing the app pool I was running under!
The App Pool was running under a service account and once I moved it to a new App Pool with just the default system account it started picking up the User ID and Password from the config.
I was trying with the command:
ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE;
But it didn't work.
I had to change it using the SQL Developer in the DBA tab.
Find the Parameter 'sec_case_sensitive_logon' and change its value to 'FALSE'
Commit your changes using the button:
It will ask the commit strategy and you have to choose both:
Click 'Apply'
I don't know if this step is required, but I also changed the user's password. (I set the same password)
In case, you don't know how to open the 'Initialization Parameters':
Open 'Oracle SQL Developer'
Go to 'View' menu and select 'DBA'
Choose a connection
And then click on 'Initialization Parameters'
For some reason (and have no idea why ) my c# code sends my username uppercased even though I write it as lowercase.
For example my username is kullaniciadi you may think uppercase of this would be KULLANICIADI but seems it's not. My server's locale is Turkish (I believe this is the reason) so uppercased version of my username becomes KULLANİCİADİ because in Turkish uppercase of i is İ and uppercase of ı is I. And this results invalid username error.
Had no control over database so can't change any settings on it.
Typing my username all uppercased solved the problem.
Also this only works in combination of accepted answer. If registry key mentioned in accepted answer is set to 1 then this answer may not work.
Spent lots of hours for this stupid thing. I'm writing this down so you won't.

How to use NModbus and C# with PLC to to turn outputs on and off

Hi all I'm using the NModbus library, and was previously running on VS2012 and then VS2010, but tried running it on VS2008 and it seems to be running better.
Here is my output when I run the code in the dos prompt
Modbus.IO.ModbusSerialTransport Write - TX: 1,16,7,208,0,3,6,0,1,0,5,0,15,149,152
Modbus.IO.ModbusRTUTransport ReadResponse - RX: 1,16,7,208,0,3,128,133
Now I do get a flickering on my PLC unit for the RX and TX when I run this script, but I do not see my outputs on my PLC going high. Here is the associated piece of code from the library
{
using (SerialPort port = new SerialPort("COM1"))
{
// configure serial port
port.BaudRate = 38400;
port.DataBits = 8;
port.Parity = Parity.Odd;
port.StopBits = StopBits.One;
port.Open();
// create modbus master
IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
byte slaveId = 1;
ushort startAddress = 2000;
//ushort[] registers = new ushort[] { 1, 2, 3 };
ushort[] registers = new ushort[] { 01, 05, 15 };
// write three registers
master.WriteMultipleRegisters(slaveId, startAddress, registers);
}
}
Can someone help me in understanding the TX and RX, and also perhaps help to point me in the direction to pinpoint where I can look to find how to set outputs high from the C# script?
It is easier to understand the TX and RX data if you convert the bytes to its hexadecimal representation.
For TX data, we have:
01 10 07 D0 00 03 06 00 01 00 05 00 0F 95 98
01 is the Modbus slave address
10 is the Modbus function code for the Write Multiple Registers function
07 D0 is the starting address (2000)
00 03 is the number of registers being written to (3)
06 is the number of bytes containing register data (each register holds 2 bytes, as you're writing to 3 registers, we have 6 bytes being transferred)
00 01 is the value being written to register 2000
00 05 is the value being written to register 2001
00 0F is the value being written to register 2002
95 98 is the calculated CRC for this frame
For RX data we have:
01 10 07 D0 00 03 80 85
The response for the Write Mulitple Registers function is just a response with the same slave address, function code, starting address and the number of registers from the request, plus the calculated CRC for the response frame (80 85).
You can get the Modbus specifications from http://www.modbus.org/specs.php. You can find the format for all request and response frames in the Modbus Application Protocol Specification.
You need to check your PLC documentation to see how the outputs are mapped to registers. As they're on/off outputs, they're probably mapped to coils, in this case you should use the Write Multiple Coils function.

ControlTransfer instruction not sending value parameter from setup packetr in LibUsbDotNet

I have a USB device that I need to be able to talk to from a .net application. The device is not a standard HID device and in order to initilise it I've been given a trace of packets from a USB Protocol Analyser / Sniffer for the packets used when intialising it on another type of machine. I need to replicate this packet sequence from my .net application to initialise the device.
Everything is working well until I get to a particular control transfer packet / class type request.
The trace I've been given states I should issue:
Control Transfer Class Type Request
21 0A 00 00 00 00 00 00
Result stall (intentional)
Control Transfer Class Tyoe Request
A1 01 01 03 00 00 40 00
Result will initiate a 64 byte transfer of data from the device to the host.
This is the code I'm using to do this:
// Transcation 6
UsbSetupPacket setup = new UsbSetupPacket(0x21, 0x0A, 0, 0, 0);
bool result = MyUsbDevice.ControlTransfer(ref setup, buffer, 0, out transferred);
Console.WriteLine("Result = {0}", result);
// Transcation 7
setup = new UsbSetupPacket(0xA1, 0x01, 0x0301, 0x0000, 0x0040);
result = MyUsbDevice.ControlTransfer(ref setup, buffer, 64, out transferred);
Console.WriteLine("Result = {0}, {1}", result, transferred);
And this is the trace I'm receiving from BusHound which is sniffing the USB data traffic for this device:
Device Phase Data Description Cmd.Phase.Ofs(rep)
------ ----- ------------------------ ---------------- ------------------
46.0 CTL 21 0a 00 00 00 00 00 00 SET IDLE 20.1.0
46.0 USTS c0000004 stall pid 20.2.0
46.0 CTL a1 01 01 03 00 00 00 00 GET REPORT 21.1.0
46.1 USTS c0000004 stall pid 22.1.0
As you can see the 0x0040 value parameter in the setup packet is not making it out even though I'm setting it. I'm relatively new to USB and to .net / LibUsbDotNet and I'm not quite sure what I'm doing wrong. I wonder if anyone can suggest anything for me to try?
Note, I'm developing on a Windows 7 64bit machine using Visual Studio 2008.
Thanks,
Rich
OK, after much investigation I found the source of the problem and it was really my lack of understanding of how LibUSBDotNet works, which isn't helped by the poor documentation for the otherwise excellent library.
The problem is that the 0x0040 should not be manually specified in the setup packet - this value appears to be irrelevant. Instead simply specify the bytes to transfer in the ControlTransfer method and also ensure that buffer is a pre-allocated suitably large byte array eg:
byte[] buffer = new byte[256];
setup = new UsbSetupPacket(0xA1, 0x01, 0x0301, 0x0000, 0x0000);
result = MyUsbDevice.ControlTransfer(ref setup, buffer, 0x0040, out transferred);
This will generate the correct control transfer packet sent to the USB device
Control Transfer Class Tyoe Request
A1 01 01 03 00 00 40 00
It appears the LibUsbDotNet does some validation on the various parameters and in the case where the buffer array isn't large enought it simply just sends something else instead (in my case 0x0000) rather than throwing an appropriate exception.

Categories