3466a8d88f74d5abc91c270013f8a9cbb2cf1bf1
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / taf / basic / BasicHttpTaf.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.basic;
23
24 import java.io.IOException;
25 import java.security.Principal;
26 import java.util.Map;
27 import java.util.TreeMap;
28
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.onap.aaf.cadi.Access;
33 import org.onap.aaf.cadi.Access.Level;
34 import org.onap.aaf.cadi.BasicCred;
35 import org.onap.aaf.cadi.CachedPrincipal;
36 import org.onap.aaf.cadi.CachedPrincipal.Resp;
37 import org.onap.aaf.cadi.CadiException;
38 import org.onap.aaf.cadi.CredVal;
39 import org.onap.aaf.cadi.CredVal.Type;
40 import org.onap.aaf.cadi.CredValDomain;
41 import org.onap.aaf.cadi.Taf;
42 import org.onap.aaf.cadi.config.Config;
43 import org.onap.aaf.cadi.filter.MapBathConverter;
44 import org.onap.aaf.cadi.principal.BasicPrincipal;
45 import org.onap.aaf.cadi.principal.CachedBasicPrincipal;
46 import org.onap.aaf.cadi.taf.HttpTaf;
47 import org.onap.aaf.cadi.taf.TafResp;
48 import org.onap.aaf.cadi.taf.TafResp.RESP;
49 import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf;
50 import org.onap.aaf.cadi.util.CSV;
51
52 /**
53  * BasicHttpTaf
54  * 
55  * This TAF implements the "Basic Auth" protocol.  
56  * 
57  * WARNING! It is true for any implementation of "Basic Auth" that the password is passed unencrypted.  
58  * This is because the expectation, when designed years ago, was that it would only be used in 
59  * conjunction with SSL (https).  It is common, however, for users to ignore this on the assumption that
60  * their internal network is secure, or just ignorance.  Therefore, a WARNING will be printed
61  * when the HTTP Channel is not encrypted (unless explicitly turned off).
62  * 
63  * @author Jonathan
64  *
65  */
66 public class BasicHttpTaf implements HttpTaf {
67     private Access access;
68     private String realm;
69     private CredVal rbac;
70     private Map<String,CredVal> rbacs = new TreeMap<>();
71     private boolean warn;
72     private long timeToLive;
73         private MapBathConverter mapIds;
74     
75     public BasicHttpTaf(Access access, CredVal rbac, String realm, long timeToLive, boolean turnOnWarning) {
76         this.access = access;
77         this.realm = realm;
78         this.rbac = rbac;
79         this.warn = turnOnWarning;
80         this.timeToLive = timeToLive;
81         String csvFile = access.getProperty(Config.CADI_BATH_CONVERT, null);
82         if(csvFile==null) {
83                 mapIds=null;
84         } else {
85                 try {
86                                 mapIds = new MapBathConverter(access, new CSV(csvFile));
87                         } catch (IOException | CadiException e) {
88                                 access.log(e,"Bath Map Conversion is not initialzed (non fatal)");
89                         }
90         }
91     }
92
93     public void add(final CredValDomain cvd) {
94         rbacs.put(cvd.domain(), cvd);
95     }
96     
97     /**
98      * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms.  
99      * @see Taf
100      */
101     public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) {
102         // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately
103         if (req instanceof BasicCred) {
104             BasicCred bc = (BasicCred)req;
105             if (bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null
106                 if (DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) {
107                     return DenialOfServiceTaf.respDenyID(access,bc.getUser());
108                 }
109                 CachedBasicPrincipal bp = new CachedBasicPrincipal(this,bc,realm,timeToLive);
110                 
111                 // Be able to do Organizational specific lookups by Domain
112                 CredVal cv = rbacs.get(bp.getDomain());
113                 if (cv==null) {
114                     cv = rbac;
115                 }
116                 
117                 // ONLY FOR Last Ditch DEBUGGING... 
118                 // access.log(Level.WARN,bp.getName() + ":" + new String(bp.getCred()));
119                 if (cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) {
120                     return new BasicHttpTafResp(access,bp,bp.getName()+" authenticated by password",RESP.IS_AUTHENTICATED,resp,realm,false);
121                 } else {
122                     //TODO may need timed retries in a given time period
123                     return new BasicHttpTafResp(access,null,buildMsg(bp,req,"user/pass combo invalid for ",bc.getUser(),"from",req.getRemoteAddr()), 
124                             RESP.TRY_AUTHENTICATING,resp,realm,true);
125                 }
126             }
127         }
128         // Get User/Password from Authorization Header value
129         String authz = req.getHeader("Authorization");
130         if (authz != null && authz.startsWith("Basic ")) {
131             if (warn&&!req.isSecure()) {
132                 access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel");
133             }
134             if(mapIds != null) {
135                 authz = mapIds.convert(access, authz);
136             }
137             try {
138                 CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive);
139                 if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) {
140                     return DenialOfServiceTaf.respDenyID(access,ba.getName());
141                 }
142                 
143                 final int at = ba.getName().indexOf('@');
144                 CredVal cv = rbacs.get(ba.getName().substring(at+1));
145                 if (cv==null) { 
146                     cv = rbac; // default
147                 }
148
149                 // ONLY FOR Last Ditch DEBUGGING... 
150                 // access.log(Level.WARN,ba.getName() + ":" + new String(ba.getCred()));
151                 if (cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) {
152                     return new BasicHttpTafResp(access,ba, ba.getName()+" authenticated by BasicAuth password",RESP.IS_AUTHENTICATED,resp,realm,false);
153                 } else {
154                     //TODO may need timed retries in a given time period
155                     return new BasicHttpTafResp(access,null,buildMsg(ba,req,"user/pass combo invalid"), 
156                             RESP.TRY_AUTHENTICATING,resp,realm,true);
157                 }
158             } catch (IOException e) {
159                 String msg = buildMsg(null,req,"Failed HTTP Basic Authorization (", e.getMessage(), ')');
160                 access.log(Level.INFO,msg);
161                 return new BasicHttpTafResp(access,null,msg, RESP.TRY_AUTHENTICATING, resp, realm,true);
162             }
163         }
164         return new BasicHttpTafResp(access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,realm,false);
165     }
166     
167     protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) {
168         StringBuilder sb = new StringBuilder();
169         if (pr!=null) {
170             sb.append("user=");
171             sb.append(pr.getName());
172             sb.append(',');
173         }
174         sb.append("ip=");
175         sb.append(req.getRemoteAddr());
176         sb.append(",port=");
177         sb.append(req.getRemotePort());
178         if (msg.length>0) {
179             sb.append(",msg=\"");
180             for (Object s : msg) {
181                 sb.append(s.toString());
182             }
183             sb.append('"');
184         }
185         return sb.toString();
186     }
187     
188     public void addCredVal(final String realm, final CredVal cv) {
189         rbacs.put(realm, cv);
190     }
191
192     public CredVal getCredVal(String key) {
193         CredVal cv = rbacs.get(key);
194         if (cv==null) {
195             cv = rbac;
196         }
197         return cv;
198     }
199     
200     @Override
201     public Resp revalidate(CachedPrincipal prin, Object state) {
202         if (prin instanceof BasicPrincipal) {
203             BasicPrincipal ba = (BasicPrincipal)prin;
204             if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) {
205                 return Resp.UNVALIDATED;
206             }
207             return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED;
208         }
209         return Resp.NOT_MINE;
210     }
211     
212     public String toString() {
213         return "Basic Auth enabled on realm: " + realm;
214     }
215
216 }