Fix sonar issues in Mapper1_0
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / taf / cert / X509Taf.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.taf.cert;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.Signature;
29 import java.security.cert.CertificateException;
30 import java.security.cert.CertificateFactory;
31 import java.security.cert.X509Certificate;
32 import java.util.ArrayList;
33
34 import javax.net.ssl.TrustManagerFactory;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37
38 import org.onap.aaf.cadi.Access;
39 import org.onap.aaf.cadi.CachedPrincipal;
40 import org.onap.aaf.cadi.CadiException;
41 import org.onap.aaf.cadi.Lur;
42 import org.onap.aaf.cadi.Symm;
43 import org.onap.aaf.cadi.Access.Level;
44 import org.onap.aaf.cadi.CachedPrincipal.Resp;
45 import org.onap.aaf.cadi.Taf.LifeForm;
46 import org.onap.aaf.cadi.config.Config;
47 import org.onap.aaf.cadi.config.SecurityInfo;
48 import org.onap.aaf.cadi.config.SecurityInfoC;
49 import org.onap.aaf.cadi.principal.TaggedPrincipal;
50 import org.onap.aaf.cadi.principal.X509Principal;
51 import org.onap.aaf.cadi.taf.HttpTaf;
52 import org.onap.aaf.cadi.taf.TafResp;
53 import org.onap.aaf.cadi.taf.TafResp.RESP;
54 import org.onap.aaf.cadi.util.Split;
55
56 public class X509Taf implements HttpTaf {
57         
58         private static final String CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION = "Certificate NOT valid for Authentication";
59         public static final CertificateFactory certFactory;
60         public static final MessageDigest messageDigest;
61         public static final TrustManagerFactory tmf;
62         private Access access;
63         private CertIdentity[] certIdents;
64 //      private Lur lur;
65         private ArrayList<String> cadiIssuers;
66         private String env;
67         private SecurityInfo si;
68
69         static {
70                 try {
71                         certFactory = CertificateFactory.getInstance("X.509");
72                         messageDigest = MessageDigest.getInstance("SHA-256"); // use this to clone
73                         tmf = TrustManagerFactory.getInstance(SecurityInfoC.SslKeyManagerFactoryAlgorithm);
74                 } catch (Exception e) {
75                         throw new RuntimeException("X.509 and SHA-256 are required for X509Taf",e);
76                 }
77         }
78         
79         public X509Taf(Access access, Lur lur, CertIdentity ... cis) throws CertificateException, NoSuchAlgorithmException, CadiException {
80                 this.access = access;
81                 env = access.getProperty(Config.AAF_ENV,null);
82                 if(env==null) {
83                         throw new CadiException("X509Taf requires Environment ("+Config.AAF_ENV+") to be set.");
84                 }
85 //              this.lur = lur;
86                 this.cadiIssuers = new ArrayList<String>();
87                 for(String ci : access.getProperty(Config.CADI_X509_ISSUERS, "").split(":")) {
88                         access.printf(Level.INIT, "Trusting Identity for Certificates signed by \"%s\"",ci);
89                         cadiIssuers.add(ci);
90                 }
91                 try {
92                         Class<?> dci = access.classLoader().loadClass("org.onap.aaf.auth.direct.DirectCertIdentity");
93                         if(dci==null) {
94                                 certIdents = cis;
95                         } else {
96                                 CertIdentity temp[] = new CertIdentity[cis.length+1];
97                                 System.arraycopy(cis, 0, temp, 1, cis.length);
98                                 temp[0] = (CertIdentity) dci.newInstance();
99                                 certIdents=temp;
100                         }
101                 } catch (Exception e) {
102                         certIdents = cis;
103                 }
104                 
105                 si = new SecurityInfo(access);
106         }
107
108         public static final X509Certificate getCert(byte[] certBytes) throws CertificateException {
109                 ByteArrayInputStream bais = new ByteArrayInputStream(certBytes);
110                 return (X509Certificate)certFactory.generateCertificate(bais);
111         }
112
113         public static final byte[] getFingerPrint(byte[] ba) {
114                 MessageDigest md;
115                 try {
116                         md = (MessageDigest)messageDigest.clone();
117                 } catch (CloneNotSupportedException e) {
118                         // should never get here
119                         return new byte[0];
120                 }
121                 md.update(ba);
122                 return md.digest();
123         }
124
125         @Override
126         public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) {
127                 // Check for Mutual SSL
128                 try {
129                         X509Certificate[] certarr = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate");
130                         if(certarr!=null && certarr.length>0) {
131                                 si.checkClientTrusted(certarr);
132                                 // Note: If the Issuer is not in the TrustStore, it's not added to the Cert list
133                                 String issuer = certarr[0].getIssuerDN().toString();
134                                 if(cadiIssuers.contains(issuer)) {
135                                         String subject = certarr[0].getSubjectDN().getName();
136                                         // avoiding extra object creation, since this is validated EVERY transaction with a Cert
137                                         int at = subject.indexOf('@');
138                                         if(at>=0) {
139                                                 int start = subject.lastIndexOf(',', at);
140                                                 if(start<0) {
141                                                         start = 0;
142                                                 }
143                                                 int end = subject.indexOf(',', at);
144                                                 if(end<0) {
145                                                         end=subject.length();
146                                                 }
147                                                 int temp;
148                                                 if(((temp=subject.indexOf("OU=",start))>=0 && temp<end) || 
149                                                    ((temp=subject.indexOf("CN=",start))>=0 && temp<end)) {
150                                                         String[] sa = Split.splitTrim(':', subject, temp+3,end);
151                                                         if(sa.length==1 || (sa.length>1 && env!=null && env.equals(sa[1]))) { // Check Environment 
152                                                                 return new X509HttpTafResp(access, 
153                                                                                 new X509Principal(sa[0], certarr[0],(byte[])null), 
154                                                                                 "X509Taf validated " + sa[0] + (sa.length<2?"":" for aaf_env " + env ), RESP.IS_AUTHENTICATED);
155                                                         }
156                                                 }
157                                                 
158                                         }
159                                 }
160                         }
161                 
162
163                         byte[] array = null;
164                         byte[] certBytes = null;
165                         X509Certificate cert=null;
166                         String responseText=null;
167                         String authHeader = req.getHeader("Authorization");
168
169                         if(certarr!=null) {  // If cert !=null, Cert is Tested by Mutual Protocol.
170                                 if(authHeader!=null) { // This is only intended to be a Secure Connection, not an Identity
171                                         for(String auth : Split.split(',',authHeader)) {
172                                                 if(auth.startsWith("Bearer ")) { // Bearer = OAuth... Don't use as Authenication
173                                                         return new X509HttpTafResp(access, null, "Certificate verified, but Bearer Token is presented", RESP.TRY_ANOTHER_TAF);
174                                                 }
175                                         }
176                                 }
177                                 cert = certarr[0];
178                                 responseText = ", validated by Mutual SSL Protocol";
179                         } else {                 // If cert == null, Get Declared Cert (in header), but validate by having them sign something
180                                 if(authHeader != null) {
181                                         for(String auth : Split.splitTrim(',',authHeader)) {
182                                                 if(auth.startsWith("x509 ")) {
183                                                         ByteArrayOutputStream baos = new ByteArrayOutputStream(auth.length());
184                                                         try {
185                                                                 array = auth.getBytes();
186                                                                 ByteArrayInputStream bais = new ByteArrayInputStream(array);
187                                                                 Symm.base64noSplit.decode(bais, baos, 5);
188                                                                 certBytes = baos.toByteArray();
189                                                                 cert = getCert(certBytes);
190                                                                 
191                                                                 /** 
192                                                                  * Identity from CERT if well know CA and specific encoded information
193                                                                  */
194                                                                 // If found Identity doesn't work, try SignedStuff Protocol
195                 //                                                                      cert.checkValidity();
196                 //                                                                      cert.--- GET FINGERPRINT?
197                                                                 String stuff = req.getHeader("Signature");
198                                                                 if(stuff==null) 
199                                                                         return new X509HttpTafResp(access, null, "Header entry 'Signature' required to validate One way X509 Certificate", RESP.TRY_ANOTHER_TAF);
200                                                                 String data = req.getHeader("Data"); 
201                 //                                                                      if(data==null) 
202                 //                                                                              return new X509HttpTafResp(access, null, "No signed Data to validate with X509 Certificate", RESP.TRY_ANOTHER_TAF);
203                 
204                                                                 // Note: Data Pos shows is "<signatureType> <data>"
205                 //                                                                      int dataPos = (stuff.indexOf(' ')); // determine what is Algorithm
206                                                                 // Get Signature 
207                                                                 bais = new ByteArrayInputStream(stuff.getBytes());
208                                                                 baos = new ByteArrayOutputStream(stuff.length());
209                                                                 Symm.base64noSplit.decode(bais, baos);
210                                                                 array = baos.toByteArray();
211                 //                                                                      Signature sig = Signature.getInstance(stuff.substring(0, dataPos)); // get Algorithm from first part of Signature
212                                                                 
213                                                                 Signature sig = Signature.getInstance(cert.getSigAlgName()); 
214                                                                 sig.initVerify(cert.getPublicKey());
215                                                                 sig.update(data.getBytes());
216                                                                 if(!sig.verify(array)) {
217                                                                         access.log(Level.ERROR, "Signature doesn't Match");
218                                                                         return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF);
219                                                                 }
220                                                                 responseText = ", validated by Signed Data";
221                                                         } catch (Exception e) {
222                                                                 access.log(e, "Exception while validating Cert");
223                                                                 return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF);
224                                                         }
225                                                 }
226                                         }
227                                 }
228                                 if(cert==null) {
229                                         return new X509HttpTafResp(access, null, "No Certificate Info on Transaction", RESP.TRY_ANOTHER_TAF);
230                                 }
231                                 
232                                 // A cert has been found, match Identify
233                                 TaggedPrincipal prin=null;
234                                 
235                                 for(int i=0;prin==null && i<certIdents.length;++i) {
236                                         if((prin=certIdents[i].identity(req, cert, certBytes))!=null) {
237                                                 responseText = prin.getName() + " matches Certificate " + cert.getSubjectX500Principal().getName() + responseText;
238                                         }
239                                 }
240         
241                                 // if Principal is found, check for "AS_USER" and whether this entity is trusted to declare
242                                 if(prin!=null) {
243                                         return new X509HttpTafResp(
244                                                 access,
245                                                 prin,
246                                                 responseText,
247                                                 RESP.IS_AUTHENTICATED);
248                                 }
249                         }
250                 } catch(Exception e) {
251                         return new X509HttpTafResp(access, null, e.getMessage(), RESP.TRY_ANOTHER_TAF); 
252                 }
253         
254                 return new X509HttpTafResp(access, null, "Certificate cannot be used for authentication", RESP.TRY_ANOTHER_TAF);
255         }
256
257         @Override
258         public Resp revalidate(CachedPrincipal prin, Object state) {
259                 return null;
260         }
261
262 }