001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hdfs.server.namenode;
019
020import com.google.common.base.Preconditions;
021import org.apache.hadoop.classification.InterfaceAudience;
022import org.apache.hadoop.classification.InterfaceStability;
023import org.apache.hadoop.fs.UnresolvedLinkException;
024import org.apache.hadoop.fs.permission.AclEntry;
025import org.apache.hadoop.fs.permission.AclEntryScope;
026import org.apache.hadoop.fs.permission.AclEntryType;
027import org.apache.hadoop.fs.permission.FsAction;
028import org.apache.hadoop.fs.permission.FsPermission;
029import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot;
030import org.apache.hadoop.hdfs.util.ReadOnlyList;
031import org.apache.hadoop.security.AccessControlException;
032import org.apache.hadoop.util.StringUtils;
033
034import java.util.List;
035import java.util.Set;
036import java.util.Stack;
037
038@InterfaceAudience.Public
039@InterfaceStability.Unstable
040public class DefaultAuthorizationProvider
041    extends AuthorizationProvider {
042
043  @Override
044  public void setUser(INodeAuthorizationInfo node, String user) {
045    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
046    int n = SerialNumberManager.INSTANCE.getUserSerialNumber(user);
047    inode.updatePermissionStatus(
048        INodeWithAdditionalFields.PermissionStatusFormat.USER, n);
049  }
050
051  @Override
052  public String getUser(INodeAuthorizationInfo node, int snapshotId) {
053    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
054    if (snapshotId != Snapshot.CURRENT_STATE_ID) {
055      return inode.getSnapshotINode(snapshotId).getUserName();
056    }
057    return INodeWithAdditionalFields.PermissionStatusFormat.
058        getUser(inode.getPermissionLong());
059  }
060
061  @Override
062  public void setGroup(INodeAuthorizationInfo node, String group) {
063    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
064    int n = SerialNumberManager.INSTANCE.getGroupSerialNumber(group);
065    inode.updatePermissionStatus(
066        INodeWithAdditionalFields.PermissionStatusFormat.GROUP, n);
067  }
068
069  @Override
070  public String getGroup(INodeAuthorizationInfo node, int snapshotId) {
071    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
072    if (snapshotId != Snapshot.CURRENT_STATE_ID) {
073      return inode.getSnapshotINode(snapshotId).getGroupName();
074    }
075    return INodeWithAdditionalFields.PermissionStatusFormat.
076        getGroup(inode.getPermissionLong());
077  }
078
079  @Override
080  public void setPermission(INodeAuthorizationInfo node, 
081      FsPermission permission) {
082    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
083    final short mode = permission.toShort();
084    inode.updatePermissionStatus(INodeWithAdditionalFields.
085        PermissionStatusFormat.MODE, mode);
086  }
087
088  @Override
089  public FsPermission getFsPermission(INodeAuthorizationInfo node, 
090      int snapshotId) {
091    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
092    if (snapshotId != Snapshot.CURRENT_STATE_ID) {
093      return inode.getSnapshotINode(snapshotId).getFsPermission();
094    }
095    return new FsPermission(inode.getFsPermissionShort());
096  }
097
098  @Override
099  public AclFeature getAclFeature(INodeAuthorizationInfo node,
100      int snapshotId) {
101    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
102    if (snapshotId != Snapshot.CURRENT_STATE_ID) {
103      return inode.getSnapshotINode(snapshotId).getAclFeature();
104    }
105    return inode.getFeature(AclFeature.class);
106  }
107
108  @Override
109  public void removeAclFeature(INodeAuthorizationInfo node) {
110    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
111    AclFeature f = inode.getAclFeature();
112    Preconditions.checkNotNull(f);
113    inode.removeFeature(f);
114  }
115
116  @Override
117  public void addAclFeature(INodeAuthorizationInfo node, AclFeature f) {
118    INodeWithAdditionalFields inode = (INodeWithAdditionalFields) node;
119    AclFeature f1 = inode.getAclFeature();
120    if (f1 != null) {
121      throw new IllegalStateException("Duplicated ACLFeature");
122    }
123    inode.addFeature(f);
124  }
125
126  @Override
127  public void checkPermission(String user, Set<String> groups,
128      INodeAuthorizationInfo[] nodes, int snapshotId,
129      boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess,
130      FsAction access, FsAction subAccess, boolean ignoreEmptyDir)
131      throws AccessControlException, UnresolvedLinkException {
132    INode[] inodes = (INode[]) nodes;
133    int ancestorIndex = inodes.length - 2;
134    for (; ancestorIndex >= 0 && inodes[ancestorIndex] == null;
135         ancestorIndex--)
136      ;
137    checkTraverse(user, groups, inodes, ancestorIndex, snapshotId);
138
139    final INode last = inodes[inodes.length - 1];
140    if (parentAccess != null && parentAccess.implies(FsAction.WRITE)
141        && inodes.length > 1 && last != null) {
142      checkStickyBit(user, inodes[inodes.length - 2], last, snapshotId);
143    }
144    if (ancestorAccess != null && inodes.length > 1) {
145      check(user, groups, inodes, ancestorIndex, snapshotId, ancestorAccess);
146    }
147    if (parentAccess != null && inodes.length > 1) {
148      check(user, groups, inodes, inodes.length - 2, snapshotId, parentAccess);
149    }
150    if (access != null) {
151      check(user, groups, last, snapshotId, access);
152    }
153    if (subAccess != null) {
154      checkSubAccess(user, groups, last, snapshotId, subAccess, ignoreEmptyDir);
155    }
156    if (doCheckOwner) {
157      checkOwner(user, last, snapshotId);
158    }
159  }
160
161  /**
162   * Guarded by {@link FSNamesystem#readLock()}
163   */
164  private void checkOwner(String user, INode inode, int snapshotId
165  ) throws AccessControlException {
166    if (inode != null && user.equals(inode.getUserName(snapshotId))) {
167      return;
168    }
169    throw new AccessControlException(
170       "Permission denied. user="
171       + user + " is not the owner of inode=" + inode);
172  }
173
174  /**
175   * Guarded by {@link FSNamesystem#readLock()}
176   */
177  private void checkTraverse(String user, Set<String> groups, INode[] inodes,
178      int last, int snapshotId) throws AccessControlException {
179    for (int j = 0; j <= last; j++) {
180      check(user, groups, inodes[j], snapshotId, FsAction.EXECUTE);
181    }
182  }
183
184  /**
185   * Guarded by {@link FSNamesystem#readLock()}
186   */
187  private void checkSubAccess(String user, Set<String> groups, INode inode,
188      int snapshotId, FsAction access, boolean ignoreEmptyDir)
189      throws AccessControlException {
190    if (inode == null || !inode.isDirectory()) {
191      return;
192    }
193
194    Stack<INodeDirectory> directories = new Stack<INodeDirectory>();
195    for (directories.push(inode.asDirectory()); !directories.isEmpty(); ) {
196      INodeDirectory d = directories.pop();
197      ReadOnlyList<INode> cList = d.getChildrenList(snapshotId);
198      if (!(cList.isEmpty() && ignoreEmptyDir)) {
199        check(user, groups, d, snapshotId, access);
200      }
201
202      for (INode child : cList) {
203        if (child.isDirectory()) {
204          directories.push(child.asDirectory());
205        }
206      }
207    }
208  }
209
210  /**
211   * Guarded by {@link FSNamesystem#readLock()}
212   */
213  private void check(String user, Set<String> groups, INode[] inodes, int i,
214      int snapshotId, FsAction access
215  ) throws AccessControlException {
216    check(user, groups, i >= 0 ? inodes[i] : null, snapshotId, access);
217  }
218
219  /**
220   * Guarded by {@link FSNamesystem#readLock()}
221   */
222  private void check(String user, Set<String> groups, INode inode,
223      int snapshotId, FsAction access) throws AccessControlException {
224    if (inode == null) {
225      return;
226    }
227    FsPermission mode = inode.getFsPermission(snapshotId);
228    AclFeature aclFeature = inode.getAclFeature(snapshotId);
229    if (aclFeature != null) {
230      List<AclEntry> featureEntries = aclFeature.getEntries();
231      // It's possible that the inode has a default ACL but no access ACL.
232      if (featureEntries.get(0).getScope() == AclEntryScope.ACCESS) {
233        checkAccessAcl(user, groups, inode, snapshotId, access, mode,
234            featureEntries);
235        return;
236      }
237    }
238    checkFsPermission(user, groups, inode, snapshotId, access, mode);
239  }
240
241  private void checkFsPermission(String user, Set<String> groups, INode inode,
242      int snapshotId, FsAction access, FsPermission mode)
243      throws AccessControlException {
244    if (user.equals(inode.getUserName(snapshotId))) { //user class
245      if (mode.getUserAction().implies(access)) {
246        return;
247      }
248    } else if (groups.contains(inode.getGroupName(snapshotId))) { //group class
249      if (mode.getGroupAction().implies(access)) {
250        return;
251      }
252    } else { //other class
253      if (mode.getOtherAction().implies(access)) {
254        return;
255      }
256    }
257    throw new AccessControlException(
258        toAccessControlString(user, inode, snapshotId, access, mode));
259  }
260
261  /**
262   * Checks requested access against an Access Control List.  This method relies
263   * on finding the ACL data in the relevant portions of {@link FsPermission} 
264   * and {@link AclFeature} as implemented in the logic of {@link AclStorage}. 
265   * This method also relies on receiving the ACL entries in sorted order.  This
266   * is assumed to be true, because the ACL modification methods in
267   * {@link AclTransformation} sort the resulting entries.
268   * <p/>
269   * More specifically, this method depends on these invariants in an ACL:
270   * - The list must be sorted.
271   * - Each entry in the list must be unique by scope + type + name.
272   * - There is exactly one each of the unnamed user/group/other entries.
273   * - The mask entry must not have a name.
274   * - The other entry must not have a name.
275   * - Default entries may be present, but they are ignored during enforcement.
276   *
277   * @param inode INode accessed inode
278   * @param snapshotId int snapshot ID
279   * @param access FsAction requested permission
280   * @param mode FsPermission mode from inode
281   * @param featureEntries List<AclEntry> ACL entries from AclFeature of inode
282   * @throws AccessControlException if the ACL denies permission
283   */
284  private void checkAccessAcl(String user, Set<String> groups, INode inode,
285      int snapshotId,  FsAction access, FsPermission mode,
286      List<AclEntry> featureEntries) throws AccessControlException {
287    boolean foundMatch = false;
288
289    // Use owner entry from permission bits if user is owner.
290    if (user.equals(inode.getUserName(snapshotId))) {
291      if (mode.getUserAction().implies(access)) {
292        return;
293      }
294      foundMatch = true;
295    }
296
297    // Check named user and group entries if user was not denied by owner entry.
298    if (!foundMatch) {
299      for (AclEntry entry : featureEntries) {
300        if (entry.getScope() == AclEntryScope.DEFAULT) {
301          break;
302        }
303        AclEntryType type = entry.getType();
304        String name = entry.getName();
305        if (type == AclEntryType.USER) {
306          // Use named user entry with mask from permission bits applied if user
307          // matches name.
308          if (user.equals(name)) {
309            FsAction masked = entry.getPermission().and(mode.getGroupAction());
310            if (masked.implies(access)) {
311              return;
312            }
313            foundMatch = true;
314            break;
315          }
316        } else if (type == AclEntryType.GROUP) {
317          // Use group entry (unnamed or named) with mask from permission bits
318          // applied if user is a member and entry grants access.  If user is a
319          // member of multiple groups that have entries that grant access, then
320          // it doesn't matter which is chosen, so exit early after first match.
321          String group = name == null ? inode.getGroupName(snapshotId) : name;
322          if (groups.contains(group)) {
323            FsAction masked = entry.getPermission().and(mode.getGroupAction());
324            if (masked.implies(access)) {
325              return;
326            }
327            foundMatch = true;
328          }
329        }
330      }
331    }
332
333    // Use other entry if user was not denied by an earlier match.
334    if (!foundMatch && mode.getOtherAction().implies(access)) {
335      return;
336    }
337
338    throw new AccessControlException(
339        toAccessControlString(user, inode, snapshotId, access, mode,
340            featureEntries));
341  }
342
343  /**
344   * Guarded by {@link FSNamesystem#readLock()}
345   */
346  private void checkStickyBit(String user, INode parent, INode inode,
347      int snapshotId) throws AccessControlException {
348    if (!parent.getFsPermission(snapshotId).getStickyBit()) {
349      return;
350    }
351
352    // If this user is the directory owner, return
353    if (parent.getUserName(snapshotId).equals(user)) {
354      return;
355    }
356
357    // if this user is the file owner, return
358    if (inode.getUserName(snapshotId).equals(user)) {
359      return;
360    }
361
362    throw new AccessControlException("Permission denied by sticky bit setting:" 
363        + " user=" + user + ", inode=" + inode);
364  }
365
366  /**
367   * @return a string for throwing {@link AccessControlException}
368   */
369  private String toAccessControlString(String user, INode inode, int snapshotId,
370      FsAction access, FsPermission mode) {
371    return toAccessControlString(user, inode, snapshotId, access, mode, null);
372  }
373
374  /**
375   * @return a string for throwing {@link AccessControlException}
376   */
377  private String toAccessControlString(String user, INode inode, int snapshotId,
378      FsAction access, FsPermission mode, List<AclEntry> featureEntries) {
379    StringBuilder sb = new StringBuilder("Permission denied: ")
380        .append("user=").append(user).append(", ")
381        .append("access=").append(access).append(", ")
382        .append("inode=\"").append(inode.getFullPathName()).append("\":")
383        .append(inode.getUserName(snapshotId)).append(':')
384        .append(inode.getGroupName(snapshotId)).append(':')
385        .append(inode.isDirectory() ? 'd' : '-')
386        .append(mode);
387    if (featureEntries != null) {
388      sb.append(':').append(StringUtils.join(",", featureEntries));
389    }
390    return sb.toString();
391  }
392
393}