Adding config file for sharing.
[iot2.git] / iotjava / iotruntime / master / ProcessJailConfig.java
1 package iotruntime.master;
2
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.io.BufferedReader;
6 import java.io.BufferedWriter;
7 import java.io.FileWriter;
8 import java.io.PrintWriter;
9 import java.io.IOException;
10 import java.nio.file.Files;
11 import java.nio.file.Paths;
12 import java.nio.charset.StandardCharsets;
13 import java.util.HashMap;
14 import java.util.Map;
15
16 /** Class ProcessJailConfig is a class that configures the compute
17  *  nodes in our network with the relevant process jail policies;
18  *  <p>
19  *  We use Tomoyo 2.5 as a Mandatory Access Control (MAC) that is
20  *  simple, easy to maintain, and lightweight (suitable for embedded
21  *  devices).
22  *
23  * @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
24  * @version     2.0
25  * @since       2017-04-07
26  */
27 public final class ProcessJailConfig {
28
29         /**
30          * ProcessJailConfig constants
31          */
32         private static final String STR_SSH_USERNAME_ROUTER = "root";
33         private static final String STR_SSH_USERNAME_HOST   = "iotuser";
34         private static final String STR_TCP_PROTOCOL        = "tcp";
35         private static final String STR_UDP_PROTOCOL        = "udp";
36         private static final String STR_TCPGW_PROTOCOL      = "tcpgw";
37         private static final String STR_NO_PROTOCOL         = "nopro";
38
39         private static final String STR_ADD_MAC_EXT             = ".tomoyo";
40         private static final String STR_MAC_POLICY_EXT          = ".tomoyo.pol";
41         private static final String STR_OBJECT_NAME             = "<object-name>";
42         private static final String STR_OBJECT_CLASS_NAME       = "<object-class-name>";
43         private static final String STR_MASTER_IP_ADDRESS       = "<master-ip-address>";
44         private static final String STR_MASTER_COM_PORT         = "<master-com-port>";
45         private static final String STR_RMI_REG_PORT            = "<rmi-reg-port>";
46         private static final String STR_RMI_STUB_PORT           = "<rmi-stub-port>";
47         private static final String STR_DEV_IP_ADDRESS          = "<dev-ip-address>";
48         private static final String STR_DEV_COM_PORT            = "<dev-com-port>";
49         private static final String STR_DEV_PORT                        = "<dev-port>";
50         
51     private static final int INT_HTTP_PORT = 80;
52     private static final int INT_DNS_PORT  = 53;
53
54
55         /**
56          * ProcessJailConfig properties
57          */
58         private Map<String, PrintWriter> mapHostToFile;
59         private Map<String, String> mapMACtoIPAdd;
60
61
62         /**
63          * Constructor
64          */
65         public ProcessJailConfig() {
66                 // This maps hostname to file PrintWriter
67                 mapHostToFile = new HashMap<String, PrintWriter>();
68                 mapMACtoIPAdd = null;
69         }
70
71
72         /**
73          * renewPrintWriter() renews the mapHostToFile object that lists all PrintWriters
74          *
75          * @return  void
76          */
77         public void renewPrintWriter() {
78
79                 mapHostToFile = new HashMap<String, PrintWriter>();
80         }
81
82
83         /**
84          * getPrintWriter() gets the right PrintWriter object to print policies to the right file
85          *
86          * @param   strConfigHost String hostname to be configured
87          * @return  PrintWriter
88          */
89         private PrintWriter getPrintWriter(String strConfigHost) {
90
91                 // Return object if existing
92                 if (mapHostToFile.containsKey(strConfigHost)) {
93                         return mapHostToFile.get(strConfigHost);
94                 } else {
95                 // Simply create a new one if it doesn't exist
96                         FileWriter fw = null;
97                         try {
98                                 fw = new FileWriter(strConfigHost + STR_MAC_POLICY_EXT);
99                         } catch (IOException ex) {
100                                 ex.printStackTrace();
101                         }
102                         PrintWriter pwConfig = new PrintWriter(new BufferedWriter(fw));
103                         mapHostToFile.put(strConfigHost, pwConfig);
104                         return pwConfig;
105                 }
106         }
107         
108         
109         /**
110          * flush() flushes all PrintWriter objects
111          *
112          * @return  void
113          */
114         public void flush() {
115
116                 for(PrintWriter pwConfig: mapHostToFile.values()) {
117                         pwConfig.flush();
118                 }
119         }
120         
121
122         /**
123          * close() closes all PrintWriter objects
124          *
125          * @return  void
126          */
127         public void close() {
128
129                 for(PrintWriter pwConfig: mapHostToFile.values()) {
130                         pwConfig.close();
131                 }
132         }
133
134
135         /**
136          * sendMACPolicies() deploys policies on MAC implementation for process jailing
137          *
138          * @param   strConfigHost String hostname to be configured
139          * @return  void
140          */
141         public void sendMACPolicies(String strConfigHost) {
142
143                 String strCmdSend = "scp " + strConfigHost + STR_MAC_POLICY_EXT + " " + 
144                         STR_SSH_USERNAME_HOST + "@" + strConfigHost + ":~;";
145                 System.out.println(strCmdSend);
146                 runCommand(strCmdSend);
147                 String strCmdDeploy = "ssh " + STR_SSH_USERNAME_HOST + "@" + strConfigHost +
148                         " sudo tomoyo-loadpolicy -df < ~/" + strConfigHost + STR_MAC_POLICY_EXT + "; rm ~/" + strConfigHost + 
149                         STR_MAC_POLICY_EXT + ";";
150                 System.out.println(strCmdDeploy);
151                 runCommand(strCmdDeploy);
152         }
153
154
155         /**
156          * deployPolicies() method configures the policies
157          *
158          * @param   strCommand  String that contains command line
159          * @return  void
160          */
161         private void deployPolicies(String strCommand) {
162
163                 try {
164                         Runtime runtime = Runtime.getRuntime();
165                         Process process = runtime.exec(strCommand);
166                         process.waitFor();
167                 } catch (IOException ex) {
168                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
169                         ex.printStackTrace();
170                 } catch (InterruptedException ex) {
171                         System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
172                         ex.printStackTrace();
173                 }
174         }
175
176
177         /**
178          * setAddressListObject() method sets the map for IP and MAC addresses
179          * <p>
180          * This method gets the mapping from RouterConfig
181          */
182         public void setAddressListObject(Map<String, String> _mapMACtoIPAdd) {
183
184                 mapMACtoIPAdd = _mapMACtoIPAdd;
185         }
186
187
188         /**
189          * runCommand() method runs shell command
190          *
191          * @param   strCommand  String that contains command line
192          * @return  void
193          */
194         private void runCommand(String strCommand) {
195
196                 try {
197                         Runtime runtime = Runtime.getRuntime();
198                         Process process = runtime.exec(strCommand);
199                         process.waitFor();
200                 } catch (IOException ex) {
201                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
202                         ex.printStackTrace();
203                 } catch (InterruptedException ex) {
204                         System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
205                         ex.printStackTrace();
206                 }
207         }
208
209
210         /**
211          * getAddressList() method gets list of IP addresses
212          * <p>
213          * This method sends an inquiry to the router to look for
214          * the list of DHCP leased addresses and their mapping to MAC
215          * addresses
216          *
217          * @param  strRouterAddress  String that contains address of router
218          */
219         public void getAddressList(String strRouterAddress) {
220
221                 try {
222                         // We can replace "cat /tmp/dhcp.leases" with "cat /proc/net/arp"
223                         String cmd = "ssh " + STR_SSH_USERNAME_ROUTER + "@" + strRouterAddress +
224                          " cat /tmp/dhcp.leases";
225                         Runtime runtime = Runtime.getRuntime();
226                         Process process = runtime.exec(cmd);
227
228                         InputStream inStream = process.getInputStream();
229                         InputStreamReader isReader = new InputStreamReader(inStream);
230                         BufferedReader bReader = new BufferedReader(isReader);
231                         String strRead = null;
232                         while((strRead = bReader.readLine()) != null){
233                                 String[] str = strRead.split(" ");
234                                 mapMACtoIPAdd.put(str[1], str[2]);
235                         }
236                 } catch (IOException ex) {
237                         System.out.println("RouterConfig: IOException: " + ex.getMessage());
238                         ex.printStackTrace();
239                 }
240         }
241
242
243         /**
244          * getIPFromMACAddress() method gets IP from MAC address
245          *
246          * @return  String  String that contains IP address from the MAC-IP mapping
247          */      
248         public String getIPFromMACAddress(String strMACAddress) {
249
250                 String strIPAddress = mapMACtoIPAdd.get(strMACAddress);
251                 if (strIPAddress == null) {
252                         throw new Error("RouterConfig: MAC address " + strMACAddress + 
253                                 " not found on the list! Please check if device is present in /tmp/dhcp.leases!");
254                 }
255                 return strIPAddress;
256         }
257
258
259         /**
260          * readFile() read the entire file and return a string
261          *
262          * @return  String  String that contains the content of the file
263          */      
264         public String readFile(String filePath) {
265
266                 String retStr = null;
267                 try {
268                         retStr = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
269                 } catch (IOException ex) {
270                         ex.printStackTrace();
271                 }
272                 return retStr;
273         }
274
275
276         /**
277          * configureProcessJailDeviceDriverPolicies() method configures the main MAC policies
278          * <p>
279          * This method configures the main policies between controller and device driver
280          *
281          * @param   strConfigHost                       String hostname to be configured
282          * @param   strObjectName                       String object name
283          * @param   strObjectClassName          String object class name
284          * @param   strFileName                         String policy file path and name
285          * @param   strMasterIPAddress          String master IP address
286          * @param   iComPort                            Integer communication port (controller-driver)
287          * @param   iRMIRegPort                         Integer RMI registry port
288          * @param   iRMIStubPort                        Integer RMI stub port
289          * @return  void
290          */
291         public void configureProcessJailDeviceDriverPolicies(String strConfigHost, String strObjectName, String strObjectClassName, 
292                         String strFileName, String strMasterIPAddress, int iComPort, int iRMIRegPort, int iRMIStubPort) {
293
294                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
295                 String strPolicyList = readFile(strFileName);
296                 // Replace the strings with the actual values
297                 String strNewPolicyList = strPolicyList.replace(STR_OBJECT_NAME, strObjectName).
298                         replace(STR_OBJECT_CLASS_NAME, strObjectClassName).
299                         replace(STR_MASTER_IP_ADDRESS, strMasterIPAddress).
300                         replace(STR_MASTER_COM_PORT, String.valueOf(iComPort));
301                 pwConfig.println("\n");
302                 pwConfig.print(strNewPolicyList);
303                 pwConfig.println("network inet stream bind/listen :: " + iRMIRegPort);
304                 pwConfig.println("network inet stream bind/listen :: " + iRMIStubPort);
305         }
306
307
308         /**
309          * configureProcessJailDevicePolicies() method configures the device MAC policies
310          * <p>
311          * This method configures the device policies between device driver and device
312          *
313          * @param   strConfigHost                       String hostname to be configured
314          * @param   strProtocol                         String protocol name
315          * @param       iDeviceComPort                  Integer device communication port
316          * @param   strDeviceIPAddress          String device IP address
317          * @param   iDevicePort                         Integer device port
318          * @return  void
319          */
320         public void configureProcessJailDevicePolicies(String strConfigHost, String strProtocol,
321                         int iDeviceComPort, String strDeviceIPAddress, int iDevicePort) {
322
323                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
324                 if (strProtocol.equals(STR_TCP_PROTOCOL)) {
325                         pwConfig.println("network inet stream connect ::ffff:" + strDeviceIPAddress + " " + String.valueOf(iDevicePort));
326                 } else {
327                         pwConfig.println("network inet dgram bind :: " + String.valueOf(iDeviceComPort));
328                         pwConfig.println("network inet dgram send ::ffff:" + strDeviceIPAddress + " " + String.valueOf(iDevicePort));
329                 }
330         }
331
332
333         /**
334          * configureProcessJailDevicePolicies() method configures the device MAC policies
335          * <p>
336          * This method configures the device policies between device driver and device
337          *
338          * @param   strConfigHost                       String hostname to be configured
339          * @param   strRouterAddress            String router address
340          * @param   iPort                                       Integer port
341          * @return  void
342          */
343         public void configureProcessJailGWDevicePolicies(String strConfigHost, String strRouterAddress, String strDeviceIPAddress, int iPort) {
344
345                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
346                 pwConfig.println("file read /home/iotuser/iot2/iotjava/iotruntime/\\*.jks");
347                 pwConfig.println("file read /etc/resolv.conf");
348                 pwConfig.println("file read /etc/hosts");
349         pwConfig.println("network inet stream connect ::ffff:" + strDeviceIPAddress + " " + String.valueOf(INT_HTTP_PORT));     // HTTP access for this address
350                 pwConfig.println("network inet dgram send " + strRouterAddress + " " + String.valueOf(iPort));
351         }
352
353
354         /**
355          * configureProcessJailDeviceDriverInetAddressPolicies() method configures the device MAC policies
356          * <p>
357          *
358          * @param   strConfigHost       String hostname to be configured
359          * @param   strAddress          String device IP address
360          * @return  void
361          */
362         public void configureProcessJailInetAddressPolicies(String strConfigHost, String strRouterAddress, String strAddress) {
363
364                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
365                 pwConfig.println("file read /etc/resolv.conf");
366                 pwConfig.println("file read /etc/hosts");
367                 pwConfig.println("file read /etc/host.conf");
368                 pwConfig.println("network inet dgram send " + strRouterAddress + " " + String.valueOf(INT_DNS_PORT));   // TCP/UDP access through router
369                 pwConfig.println("network inet stream connect ::ffff:" + strAddress + " " + String.valueOf(INT_HTTP_PORT));     // HTTP access for this address
370         }
371
372
373         /**
374          * configureProcessJailControllerPolicies() method configures the main MAC policies for controller
375          *
376          * @param   strControllerName           String controller name to be configured
377          * @param   strFileName                         String policy file path and name
378          * @param   strMasterIPAddress          String master IP address
379          * @param   iComPort                            Integer communication port (controller-driver)
380          * @return  void
381          */
382         public void configureProcessJailControllerPolicies(String strControllerName, String strFileName, 
383                         String strMasterIPAddress, int iComPort) {
384
385                 PrintWriter pwConfig = getPrintWriter(strControllerName);
386                 String strPolicyList = readFile(strFileName);
387                 // Replace the strings with the actual values
388                 String strNewPolicyList = strPolicyList.replace(STR_OBJECT_NAME, strControllerName).
389                         replace(STR_OBJECT_CLASS_NAME, strControllerName).
390                         replace(STR_MASTER_IP_ADDRESS, strMasterIPAddress).
391                         replace(STR_MASTER_COM_PORT, String.valueOf(iComPort));
392                 pwConfig.println("\n");
393                 pwConfig.print(strNewPolicyList);
394         }
395
396
397         /**
398          * configureProcessJailContRMIPolicies() method configures the MAC policies for RMI ports of controller
399          *
400          * @param   strControllerName           String controller name to be configured
401          * @param   strFileName                         String policy file path and name
402          * @param   strMasterIPAddress          String master IP address
403          * @param   iComPort                            Integer communication port (controller-driver)
404          * @return  void
405          */
406         public void configureProcessJailContRMIPolicies(String strControllerName, String strDeviceDriverIPAddress, 
407                         int iRMIRegPort, int iRMIStubPort) {
408
409                 PrintWriter pwConfig = getPrintWriter(strControllerName);
410                 // Replace the strings with the actual values
411                 pwConfig.println("network inet stream connect ::ffff:" + strDeviceDriverIPAddress + " " + String.valueOf(iRMIRegPort));
412                 pwConfig.println("network inet stream connect ::ffff:" + strDeviceDriverIPAddress + " " + String.valueOf(iRMIStubPort));
413         }
414
415
416         /**
417          * combineAdditionalMACPolicy() method combines the additional MAC policies into the right host policy file
418          *
419          * @param   strConfigHost                       String hostname to be configured
420          * @param   strFileName                         String policy file path and name
421          * @return  void
422          */
423         public void combineAdditionalMACPolicy(String strMACCfgPath, String strObjectName, String strConfigHost) {
424
425                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
426                 String strPolicyList = readFile(strMACCfgPath + strObjectName + STR_ADD_MAC_EXT);
427                 pwConfig.println(strPolicyList);
428         }
429
430
431         /**
432          * combineControllerMACPolicies() method combines the controller MAC policies into the right host policy file
433          *
434          * @param   strConfigHost                       String hostname to be configured
435          * @param   strFileName                         String policy file path and name
436          * @return  void
437          */
438         public void combineControllerMACPolicies(String strConfigHost, String strObjectControllerName, String strFileName) {
439
440                 PrintWriter pwConfig = getPrintWriter(strConfigHost);
441                 PrintWriter pwCont = getPrintWriter(strObjectControllerName);
442                 pwCont.close();
443                 String strPolicyList = readFile(strFileName);
444                 pwConfig.println(strPolicyList);
445                 runCommand("rm -rf " + strFileName);
446         }
447 }
448
449