Improve cadi-core coverage
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / CmdLine.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi;
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.io.InputStreamReader;
31 import java.security.NoSuchAlgorithmException;
32
33 import org.onap.aaf.cadi.util.Chmod;
34 import org.onap.aaf.cadi.util.JsonOutputStream;
35
36
37
38 /**
39  * A Class to run on command line to determine suitability of environment for certain TAFs.
40  * 
41  * For instance, CSP supports services only in certain domains, and while dynamic host
42  * lookups on the machine work in most cases, sometimes, names and IPs are unexpected (and
43  * invalid) for CSP because of multiple NetworkInterfaces, etc
44  * 
45  * @author Jonathan
46  *
47  */
48 public class CmdLine {
49
50         private static boolean systemExit = true;
51         /**
52          * @param args
53          */
54         public static void main(String[] args) {
55                 if(args.length>0) {
56                         if("digest".equalsIgnoreCase(args[0]) && (args.length>2 || (args.length>1 && System.console()!=null))) {
57                                 String keyfile;
58                                 String password;
59                                 if(args.length>2) {
60                                         password = args[1];
61                                         keyfile = args[2];
62                                         if("-i".equals(password)) {
63                                                 int c;
64                                                 StringBuilder sb = new StringBuilder();
65                                                 try {
66                                                         while((c=System.in.read())>=0) {
67                                                                 sb.append((char)c);
68                                                         }
69                                                 } catch (IOException e) {
70                                                         e.printStackTrace();
71                                                 }
72                                                 password = sb.toString();
73                                         }
74                                 } else {
75                                         keyfile = args[1];
76                                         password = new String(System.console().readPassword("Type here (keystrokes hidden): "));
77                                 }
78
79                                 try {
80                                         Symm symm;
81                                         FileInputStream fis = new FileInputStream(keyfile);
82                                         try {
83                                                 symm = Symm.obtain(fis);
84                                         } finally {
85                                                 fis.close();
86                                         }
87                                         symm.enpass(password, System.out);
88                                         System.out.println();
89                                         System.out.flush();
90                                         return;
91                                         /*  testing code... don't want it exposed
92                                         System.out.println(" ******** Testing *********");
93                                         for(int i=0;i<100000;++i) {
94                                                 System.out.println(args[1]);
95                                                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
96                                                 b64.enpass(args[1], baos);
97                                                 String pass; 
98                                                 System.out.println(pass=new String(baos.toByteArray()));
99                                                 ByteArrayOutputStream reconstituted = new ByteArrayOutputStream();
100                                                 b64.depass(pass, reconstituted);
101                                                 String r = reconstituted.toString();
102                                                 System.out.println(r);
103                                                 if(!r.equals(args[1])) {
104                                                         System.err.println("!!!!! STOP - ERROR !!!!!");
105                                                         return;
106                                                 }
107                                                 System.out.println();
108                                         }
109                                         System.out.flush();
110                                         */
111                                          
112                                 } catch (IOException e) {
113                                         System.err.println("Cannot digest password");
114                                         System.err.println("   \""+ e.getMessage() + '"');
115                                 }
116 // DO NOT LEAVE THIS METHOD Compiled IN CODE... Do not want looking at passwords on disk too easy
117 // Jonathan.  Oh, well, Deployment services need this behavior.  I will put this code in, but leave it undocumented. 
118 // One still needs access to the keyfile to read.
119 // July 2016 - thought of a tool "CMPass" to regurgitate from properties, but only if allowed.
120                         } else if("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) {
121                                 try {
122                                         Symm symm;
123                                         FileInputStream fis = new FileInputStream(args[2]);
124                                         try {
125                                                 symm = Symm.obtain(fis);
126                                         } finally {
127                                                 fis.close();
128                                         }
129                                         boolean isFile = false;
130                                         if("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) {
131                                                 BufferedReader br;
132                                                 if(isFile) {
133                                                         if(args.length<4) {
134                                                                 System.err.println("Filename in 4th position");
135                                                                 return;
136                                                         }
137                                                         br = new BufferedReader(new FileReader(args[3]));
138                                                 } else {
139                                                         br = new BufferedReader(new InputStreamReader(System.in));
140                                                 }
141                                                 try {
142                                                         String line;
143                                                         boolean cont = false;
144                                                         StringBuffer sb = new StringBuffer();
145                                                         JsonOutputStream jw = new JsonOutputStream(System.out);
146                                                         while((line=br.readLine())!=null) {
147                                                                 if(cont) {
148                                                                         int end;
149                                                                         if((end=line.indexOf('"'))>=0) {
150                                                                                 sb.append(line,0,end);
151                                                                                 cont=false;
152                                                                         } else {
153                                                                                 sb.append(line);
154                                                                         }
155                                                                 } else {
156                                                                         int idx;
157                                                                         if((idx = line.indexOf(' '))>=0 
158                                                                                         && (idx = line.indexOf(' ',++idx))>0
159                                                                                         && (idx = line.indexOf('=',++idx))>0
160                                                                                         ) {
161                                                                                 System.out.println(line.substring(0, idx-5));
162                                                                                 int start = idx+2;
163                                                                                 int end;
164                                                                                 if((end=line.indexOf('"',start))<0) {
165                                                                                         end = line.length();
166                                                                                         cont = true;
167                                                                                 }
168                                                                                 sb.append(line,start,end);
169                                                                         }
170                                                                 }
171                                                                 if(sb.length()>0) {
172                                                                         symm.depass(sb.toString(),jw);
173                                                                         if(!cont) {
174                                                                                 System.out.println();
175                                                                         }
176                                                                 }
177                                                                 System.out.flush();
178                                                                 sb.setLength(0);
179                                                                 if(!cont) {
180                                                                         jw.resetIndent();
181                                                                 }
182                                                         }
183                                                 } finally {
184                                                         if(isFile) {
185                                                                 br.close();
186                                                         }
187                                                 }
188                                         } else {
189                                                 symm.depass(args[1], System.out);
190                                         }
191                                         System.out.println();
192                                         System.out.flush();
193                                         return;
194                                 } catch (IOException e) {
195                                         System.err.println("Cannot regurgitate password");
196                                         System.err.println("   \""+ e.getMessage() + '"');
197                                 }
198                         } else if("encode64".equalsIgnoreCase(args[0]) && args.length>1) {
199                                 try {
200                                         Symm.base64.encode(args[1], System.out);
201                                         System.out.println();
202                                         System.out.flush();
203                                         return;
204                                 } catch (IOException e) {
205                                         System.err.println("Cannot encode Base64 with " + args[1]);
206                                         System.err.println("   \""+ e.getMessage() + '"');
207                                 }
208                         } else if("decode64".equalsIgnoreCase(args[0]) && args.length>1) {
209                                 try {
210                                         Symm.base64.decode(args[1], System.out);
211                                         System.out.println();
212                                         System.out.flush();
213                                         return;
214                                 } catch (IOException e) {
215                                         System.err.println("Cannot decode Base64 text from " + args[1]);
216                                         System.err.println("   \""+ e.getMessage() + '"');
217                                 }
218                         } else if("encode64url".equalsIgnoreCase(args[0]) && args.length>1) {
219                                 try {
220                                         Symm.base64url.encode(args[1], System.out);
221                                         System.out.println();
222                                         System.out.flush();
223                                         return;
224                                 } catch (IOException e) {
225                                         System.err.println("Cannot encode Base64url with " + args[1]);
226                                         System.err.println("   \""+ e.getMessage() + '"');
227                                 }
228                         } else if("decode64url".equalsIgnoreCase(args[0]) && args.length>1) {
229                                 try {
230                                         Symm.base64url.decode(args[1], System.out);
231                                         System.out.println();
232                                         System.out.flush();
233                                         return;
234                                 } catch (IOException e) {
235                                         System.err.println("Cannot decode Base64url text from " + args[1]);
236                                         System.err.println("   \""+ e.getMessage() + '"');
237                                 }
238                         } else if("md5".equalsIgnoreCase(args[0]) && args.length>1) {
239                                 try {
240                                         System.out.println(Hash.hashMD5asStringHex(args[1]));
241                                         System.out.flush();
242                                 } catch (NoSuchAlgorithmException e) {
243                                         System.err.println("Cannot hash MD5 from " + args[1]);
244                                         System.err.println("   \""+ e.getMessage() + '"');
245                                 }
246                                 return;
247                         } else if("sha256".equalsIgnoreCase(args[0]) && args.length>1) {
248                                 try {
249                                         if(args.length>2) {
250                                                 int max = args.length>7?7:args.length;
251                                                 for(int i=2;i<max;++i) {
252                                                         int salt = Integer.parseInt(args[i]);
253                                                         System.out.println(Hash.hashSHA256asStringHex(args[1],salt));
254                                                 }
255                                         } else { 
256                                                 System.out.println(Hash.hashSHA256asStringHex(args[1]));
257                                         }
258                                 } catch (NoSuchAlgorithmException e) {
259                                         System.err.println("Cannot hash SHA256 text from " + args[1]);
260                                         System.err.println("   \""+ e.getMessage() + '"');
261                                 }
262                                 System.out.flush();
263                                 return;
264                         } else if("keygen".equalsIgnoreCase(args[0])) {
265                                 try {
266                                         if(args.length>1) {
267                                                 File f = new File(args[1]);
268                                                 FileOutputStream fos = new FileOutputStream(f);
269                                                 try {
270                                                         fos.write(Symm.keygen());
271                                                         fos.flush();
272                                                 } finally {
273                                                         fos.close();
274                                                         Chmod.to400.chmod(f);
275                                                 }
276                                         } else {
277                                                 // create a Symmetric Key out of same characters found in base64
278                                                 System.out.write(Symm.keygen());
279                                                 System.out.flush();
280                                         }
281                                         return;
282                                 } catch (IOException e) {
283                                         System.err.println("Cannot create a key " + args[0]);
284                                         System.err.println("   \""+ e.getMessage() + '"');
285                                 }
286                         
287                         } else if("passgen".equalsIgnoreCase(args[0])) {
288                                 int numDigits;
289                                 if(args.length <= 1) {
290                                         numDigits = 24;
291                                 } else {
292                                         numDigits = Integer.parseInt(args[1]); 
293                                         if(numDigits<8)numDigits = 8;
294                                 }
295                                 String pass;
296                                 boolean noLower,noUpper,noDigits,noSpecial,repeatingChars,missingChars;
297                                 do {
298                                         pass = Symm.randomGen(numDigits);
299                                         missingChars=noLower=noUpper=noDigits=noSpecial=true;
300                                         repeatingChars=false;
301                                         int c=-1,last;
302                                         for(int i=0;i<numDigits;++i) {
303                                                 last = c;
304                                                 c = pass.charAt(i);
305                                                 if(c==last) {
306                                                         repeatingChars=true;
307                                                         break;
308                                                 }
309                                                 if(noLower) {
310                                                         noLower=!(c>=0x61 && c<=0x7A);
311                                                 } 
312                                                 if(noUpper) {
313                                                         noUpper=!(c>=0x41 && c<=0x5A);
314                                                 } 
315                                                 if(noDigits) {
316                                                         noDigits=!(c>=0x30 && c<=0x39);
317                                                 } 
318                                                 if(noSpecial) {
319                                                         noSpecial = "+!@#$%^&*(){}[]?:;,.".indexOf(c)<0;
320                                                 } 
321                                                 
322                                                 missingChars = (noLower || noUpper || noDigits || noSpecial);
323                                         }
324                                 } while(missingChars || repeatingChars);
325                                 System.out.println(pass.substring(0,numDigits));
326                         } else if("urlgen".equalsIgnoreCase(args[0])) {
327                                 int numDigits;
328                                 if(args.length <= 1) {
329                                         numDigits = 24;
330                                 } else {
331                                         numDigits = Integer.parseInt(args[1]); 
332                                 }
333                                 System.out.println(Symm.randomGen(Symm.base64url.codeset, numDigits).substring(0,numDigits));
334                         }
335                 } else {
336                         System.out.println("Usage: java -jar <this jar> ...");
337                         System.out.println("  keygen [<keyfile>]                     (Generates Key on file, or Std Out)");
338                         System.out.println("  digest [<passwd>|-i|] <keyfile>        (Encrypts Password with \"keyfile\"");
339                         System.out.println("                                          if passwd = -i, will read StdIin");
340                         System.out.println("                                          if passwd is blank, will ask securely)");
341                         System.out.println("  passgen <digits>                       (Generate Password of given size)");
342                         System.out.println("  urlgen <digits>                        (Generate URL field of given size)");
343                         System.out.println("  csptest                                (Tests for CSP compatibility)");
344                         System.out.println("  encode64 <your text>                   (Encodes to Base64)");
345                         System.out.println("  decode64 <base64 encoded text>         (Decodes from Base64)");
346                         System.out.println("  encode64url <your text>                (Encodes to Base64 URL charset)");
347                         System.out.println("  decode64url <base64url encoded text>   (Decodes from Base64 URL charset)");
348                         System.out.println("  sha256 <text> <salts(s)>               (Digest String into SHA256 Hash)");
349                         System.out.println("  md5 <text>                             (Digest String into MD5 Hash)");
350                 }
351                 if (systemExit) {
352                         System.exit(1);
353                 }
354         }
355         
356         public static void setSystemExit(boolean shouldExit) {
357                 systemExit = shouldExit;
358         }
359         
360 }