CSCI 1600 Embedded and Real Time Software Lecture
CSCI 1600: Embedded and Real Time Software Lecture 21: Networking, IPC, Fault Tolerance, Security Steven Reiss, Fall 2019
Interprocess Communication Multiple tasks need to communicate We’ve covered shared memory Using synchronization where necessary When is synchronization necessary? What other means are there? Can we combine communication and synchronization? And have the underlying system ensure it is correct 2 Lecture 25: Networking 5/20/2021
Semaphores We saw semaphores as a synchronization mechanism Protect a synchronized region Protect a set of resources Protect a producer-consumer queue They can also be used for communication When the amount of information is small Flag to let another task run Only need semaphore, no shared variable 3 Lecture 25: Networking 5/20/2021
Are Semaphores Sufficient? Semaphores are low level and error-prone Getting communications and synchronization right Can be tricky Can lead to hard to find and replicate problems Only a small amount of information passed Or you need to do synchronization Higher level abstractions can be easier to use And can be supported by a RT operating system What abstractions are appropriate? How do you send messages to others? 4 Lecture 25: Networking 5/20/2021
Mailboxes What it is A synchronized holder for a single message Operations create – initialize a mailbox structure accept – takes in a message if there pend – waits for a message post – sends a message Messages void * (arbitrary pointer) 5 Lecture 25: Networking 5/20/2021
Mailbox Implementation Mutex for operations Queue of waiting tasks Create: set up everything, empty mailbox Accept: check if mailbox is empty, if not, empty it Pend: Wait until the mailbox is non-empty Put task on wait queue for mailbox Then get message and return it Conflicts can be FIFO, priority-based, random 6 Lecture 25: Networking 5/20/2021
Mailbox Implementation Post: If queued tasks, find proper waiter and remove from queue Insert message into mailbox Let that task continue Else if there already is a message, return error Else save message and return Note that all operations are synchronized appropriately What mailboxes can’t do Multiple messages (but can prioritize) Blocking on post 7 Lecture 25: Networking 5/20/2021
Message Queues Similar to mailboxes Differences More than one message at a time Can be dynamic or fixed maximum sized Messages are void* again Block on send At least optionally 8 Lecture 25: Networking 5/20/2021
Message Queue Implementation What does this look like Synchronized producer consumer queue Handling multiple readers and writers What this doesn’t handle Variable sized messages Communication without shared memory 9 Lecture 25: Networking 5/20/2021
Pipes Similar to message queues except Handle varying sized messages May be entirely byte oriented May take <length, data> for messages Can work across processes if messages lack pointers Can work across machines But have to be wary of endian problems 10 Lecture 25: Networking 5/20/2021
Higher Level Abstractions Imply higher level bugs Bugs are less likely to be synchronization related Data-oriented problems to watch out for Using the wrong queue/pipe/mailbox Misinterpreting the passed data “Ownership” of passed pointers Wanting to ignore duplicate messages 11 Lecture 25: Networking 5/20/2021
Wider Scale Communications Might want to do more Communicate between processes Communicate between devices (e. g. in a car) Means for doing so Attached devices: point-to-point communication Busses Ethernet: MAC (Media Access Control), UDP Ethernet: TCP, IP 12 Lecture 25: Networking 5/20/2021
Commonalities Framing: putting messages together Error detection Flow control Reliability and guarantees Bus “arbitrarion” / MAC protocols 13 Lecture 25: Networking 5/20/2021
Point-to-Point Framing Sentinals Special bytes at beginning and end of message Escaped when inside a packet Length counts Encode length of the packets explicitly Bit errors may introduce big mistakes Clock-based Each frame is t microseconds long Keep clocks synchronized with transitions 14 Lecture 25: Networking 5/20/2021
Example: RS 232 Serial Ports Many variants exist, 2 wire is simplest A byte is encoded as 0 bbbb 1 (10 bits per byte) bbbb is LSB first Leave TX asserted until next byte Software flow control: XON, XOFF Hardware flow control Two extra wires: RTS, CTS 15 Lecture 25: Networking 5/20/2021
Internetworking Embedded web server interface IP cameras, switches, … Post information to a server Sensors, … Data from network shares Music player, web radio Act as browsable share (Ti. Vo) Home automation, Vo. IP, alarms 16 Lecture 25: Networking 5/20/2021
Internetworking UDP (covered in CSCI 1680) Not very different from interacting with a bus Best effort delivery (no reliability guarantees, acks) You manage retries, assembly/disassembly, congestion, acks Good for sensor updates, etc. TCP/IP Similar to a IPC pipe Adds reliability, byte stream interface Internally manages retries, ordering, etc. Web services, simple APIs 17 Lecture 25: Networking 5/20/2021
TCP/IP Sockets are like 2 -way pipes Both sides can read/write independently Sockets are address by host-port Connection to a socket Create socket on the server Bind it to a known port (on the known host) Do an accept on the socket Create a socket on the client Connect to know server socket (connect) operation Server does accept on its socket This yields a new socket bound to that client 18 Lecture 25: Networking 5/20/2021
TCP/IP Lightweight implementation exist (even for Arduino) Library interface for lw. IP (Light Weight IP) ip_input(pbuf, netif) Takes an IP packet and the network interface as args Does TCP/IP processing for the packet tcp_tmr() Should be called every 100 ms Does all TCP timer-base processing such as retransmission Event-based callbacks This is not sockets, but it is TCP/IP 19 Lecture 25: Networking 5/20/2021
lw. IP Basics Initialization: tcp_init Manage all TCP connections tcp_tmr() Must be called every 1250 milliseconds sys_check_timeout() Calls tcp_tmr and other network related timers 20 Lecture 25: Networking 5/20/2021
lw. IP Server Connection tcp_new : create a PCB for a new socket tcp_bind : bind that socket to a port on this host tcp_listen : listen for connections tcp_accept : specify a callback to call Passed routine called when someone tries to connect tcp_accepted : called from the routine to accept the connection 21 Lecture 25: Networking 5/20/2021
lw. IP Client Connection tcp_new : create new PCB (socket) tcp_bind : bind the socket to target host/port tcp_connect : establish the connection Provides callback function Called when connected Or if there is an error in the connection 22 Lecture 25: Networking 5/20/2021
lw. IP Sending Data tcp_sent : specify callback function Called when data acknowledged by remote host tcp_sndbuf : return maximum data that can be sent Space in the output queue tcp_write : enqueues the data for write Can be via copy or in-place tcp_output : forces data to be sent 23 Lecture 25: Networking 5/20/2021
lw. IP Receiving Data tcp_recv : specifies a callback function Function called when data is received Or when there is an error (connection closed) tcp_recved : acknowledges data Needs to be called by callback routine to indicate data read 24 Lecture 25: Networking 5/20/2021
lw. IP Other Functions tcp_poll : handle idle connections tcp_close : close a connection tcp_abort : forcibly close a connection tcp_err : register an error handling callback 25 Lecture 25: Networking 5/20/2021
Simple Web Server Assuming the host IP is known Create a server socket on port 80 Listen for connections Read message from connection Should be header + body Simple message = header only Decode header, branch on URL Compute output page Send reply on the connection HTTP header + HTML body 26 Lecture 25: Networking 5/20/2021
Sample Code: Minimal Server main() { struct tcp_pcb * pcb my_accept(void * arg, struct tcp_tcb_new(); tcp_pcb * pcb) { tcp_bind(pcb, NULL, 80); tcp_listen(pcb); tcp_recv(pcb, my_recv, NULL); } tcp_accept(pcb, my_accept, NULL); /* main loop */ my_recv(void * arg, } struct tcp_pcb *pcb, struct pbuf * p) { // do something with packet p } 27 Lecture 25: Networking 5/20/2021
Simple Web Communicator To send periodic updates Put together a message Simple HTTP header URL using ? x=v 1&y=v 2 to encode data Connect to <SERVER HOST: 80> Send the message Close connection Alternatives Use arbitrary message format Use arbitrary host/port for the server Send and receive messages in that format 28 Lecture 25: Networking 5/20/2021
Fault Tolerance We’ve talked about proving properties of systems This can’t always be done And even so, it is an approximation Assumes program is correct Assumes real world model is correct Assumes computer and other hardware work correctly And you can’t prove everything Embedded systems need to be fault tolerant No other recourse after failure 29 Lecture 35: Security 5/20/2021
Fault Modeling What can fail How things can fail (failure modes) Why things might fail (random or combined) Faults might be permanent, intermittent, or transient Faults might show up in different ways 30 Lecture 35: Security 5/20/2021
Responding to Faults Fault confinement Limit the effect of a fault to a local subsystem Defensive programming Fault detection and location Self tests If transient, get enough information for later analysis Fault masking Hide the effect of faults Retry Transient faults might go away Disk and memory problems may be transient 31 Lecture 35: Security 5/20/2021
Fault Avoidance Don’t write buggy code Serious testing, defensive programming Verification & Validation Avoid running devices at their limits You will still have faults 32 Lecture 35: Security 5/20/2021
Fault Detection and Recovery Systems that need to be fault-tolerant Extreme defensive programming Error checking codes (checksums) for messages Self-checking and fail-safe logic Watchdog timers and time-outs Consistency and capability checks Duplication (redundancy) This is important in critical, unsupervised systems 33 Lecture 35: Security 5/20/2021
Redundancy Triple modular redundancy Hardware is replicated three times Outcome of each module (high-level routine) is a vote If 2 agree on the answer, it is chosen This fails when All 3 disagree (fail-stop) Two modules fail together (byzantine) The voting mechanism fails Can handle k failures by having higher number of modules 34 Lecture 35: Security 5/20/2021
Space Shuttle Redundancy Five computer implement the system Four make up the primary system Normally in command; Simultaneously execute identical code Synchronize on I/O; Actuation is a physical vote Priority-based OS The fifth system is the backup Completely independent implementation Normally operates in listen-mode; Requires a manual switch-over OS is time-sliced, not priority scheduled Still have problems Same language, same compiler 35 Lecture 35: Security 5/20/2021
Fault Recovery What to do if something goes wrong Keep the system running Put the system into a stable state Watchdog timer Monitor routine of sorts Task code periodically sets a flag Watchdog (high priority) checks and unsets the flag If flag is unset, restart the system Care needed to not make things worse 36 Lecture 35: Security 5/20/2021
Fault Recovery Self-checking software With checkpoint and rollback Correct data defects in memory and continue Adaptive software “Learning” software Safe backup state Failure isn’t just CPU failure Might not want to reboot from stored state Reset-reboot switches 37 Lecture 35: Security 5/20/2021
Fault-Based Disk Partitioning Flash-based devices Four disk partitions Boot partition that is never touched Two OS partitions Usually mounted read-only Upgrades are written to the spare partition Upgrade partition is then remounted read-only and marked clean Boot partition will not boot from unclean partition Can switch over to other partition if necessary One data partition All data is soft-state 38 Lecture 35: Security 5/20/2021
Security Why worry about security in an embedded app? Examples of security problems 39 Lecture 35: Security 5/20/2021
Security Problems Allowing external users to break the device Allowing unauthorized control Allowing others to take over the device Unintentional usage Providing access to private information 40 Lecture 35: Security 5/20/2021
Threat Models The first step toward security is understanding threats What are you trying to prevent What data/actions are important Who are you trying to protect Who are the potential attackers Cost model for threats Anything can be prevented, but at a cost Anything can be attacked, but at a cost 41 Lecture 35: Security 5/20/2021
Remote Interfaces If the device has no remote interface Then changes require physical access Is this true? Physical access implies one can do anything Still want to protect users from themselves If the device has a remote interface Can be direct (socket connection for example) Can be web-based (using browser) 42 Lecture 35: Security 5/20/2021
Remote Interface Unauthorized access Bad checking of logins Bad checking of permission levels Illegal inputs That can break the code That can change the code Man-in-the-Middle attacks Web Interface XSS attacks 43 Lecture 35: Security 5/20/2021
Logging In Common operation Should be easy What are the problems? What are the operations to be concerned with? Registration (initial name & password) Log in (provide name & password to validate) Access while logged in 44 CS 132 Lecture 26: Security II 5/20/2021
Logging In: Threat Model Spoofing URLs Sending lots of requests Wi-Fi snooping Internet snooping Reading logs Man-in-the-middle attacks Phishing attacks Brute force Loss of database (SQL injection attack; stolen laptop) 45 CS 132 Lecture 26: Security II 5/20/2021
Code Attacks What is a buffer overflow What can you do with it? 46 Lecture 35: Security 5/20/2021
Buffer Overflow Attack Code: void function(char* text) { Stack (high to low) 8888: <ptr to text> char buf[1000]; 8884: <return address> strcpy(buf, text); 8880: <old stack ptr> // do some editing of buf 7880: buf[0. . 999] // save result } 47 CS 132 Lecture 26: Security II 5/20/2021
Preventing Buffer Overflow Check sizes of data before putting in array Reads, copies, inputs Randomize code locations between runs Don’t let data pages be executable Static checkers 48 CS 132 Lecture 26: Security II 5/20/2021
Encrypted Connections Encrypt all communication Simpler solution than trying to encrypt password Between the browser and the server Handles some of the issues raised with passwords Handles other problems as well Credit card numbers and other private information Encrypted communications are relatively standard Clients needs to agree on how to encode/decode Agreeing on an algorithm for encoding/decoding Agreeing on a key for that algorithm 49 CS 132 Lecture 26: Security II 5/20/2021
Standard Encryption Both parties agree on a key K F(K) and F-1(K) are easy to compute If you know K But are difficult if you don’t know K May even be done in hardware Standard encryption functions available DES is probably the most common Problem: agreeing on K 50 CS 132 Lecture 26: Security II 5/20/2021
Public Key Cryptosystems Originator has two pieces of information X and Y F(string, X) = encoded string F-1(string, X) is difficult to compute F-1(string, X, Y) is easy to compute Examples Y, Z are 200 digit primes, X is Y*Z Create a string using X such that string can only be decoded knowing the factors of X Other examples are possible This is often used as part of a secure protocol Agreeing on a key for a more secure encoding 51 CS 132 Lecture 26: Security II 5/20/2021
Browser-Server Communication Can use encrypted communication in a web app HTTPS represents an encrypted (secure) connection HTTPS is just like HTTP Except that all data passed back and forth is encrypted Browser and server agree on a key Encryption is then done based on this key This is handled by the Secure Sockets Layer (SSL) SSL is not specific to web applications 52 CS 132 Lecture 26: Security II 5/20/2021
HTTPS Connections Browser makes a connection to the server SSL handshake protocol Browser sends and requests a certificate Certificates are effectively keys that can be verified as authentic This is one way public key systems are used Server replies with a certificate of its own SSL change cipher protocol Browser and server use their certificates to agree on a key Again using a variant of public key systems Communication is done securely using that key Key is only used for this particular session 53 CS 132 Lecture 26: Security II 5/20/2021
HTTPS Usage If you are sending confidential information Even just passwords Especially credit card numbers, etc. You should use HTTPS OPENSSL and other implementations exist Typically built into server and browser Different port used for secure communication Integrated into Apache using Mod_SSL for example Problem: Obtaining a certificate 54 CS 132 Lecture 26: Security II 5/20/2021
Side Channel Attacks Getting information from power usage, radiation, etc. 55 Lecture 35: Security 5/20/2021
Server Attacks Disk attacks Large files File path attacks Information flow XSS attacks SQL injection 56 Lecture 35: Security 5/20/2021
- Slides: 56