All files / src/sso auth.ts

83.13% Statements 69/83
76.67% Branches 23/30
100% Functions 4/4
82.28% Lines 65/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 1821x 1x 1x 1x 1x 1x 1x       1x                   3x 2x                 2x   2x       2x 22x                     2x     2x         33x   33x 33x 11x 11x 11x 11x     22x         22x 22x     22x   22x 22x 22x 22x 22x       33x     22x 11x 11x 11x     22x                 22x     22x 11x 11x   22x 22x 22x       22x                       22x   22x 22x   22x 11x 11x         11x     11x     11x 11x 11x 22x 11x 11x 11x     11x             11x           11x       11x                  
import createError from 'http-errors';
import { decode, encode } from 'base64-arraybuffer';
import { hexDump, getMessageType } from './misc';
import { sspi, AcceptSecurityContextInput } from '../../lib/api';
import { SSO } from './SSO';
import { ServerContextHandleManager } from './ServerContextHandleManager';
import dbg from 'debug';
import { AuthOptions, Middleware, NextFunction } from './interfaces';
import { IncomingMessage, ServerResponse } from 'http';
 
const debug = dbg('node-expose-sspi:auth');
 
/**
 * Tries to get SSO information from browser. If success, the SSO info
 * is stored under req.sso
 *
 * @export
 * @param {AuthOptions} [options={}]
 * @returns {RequestHandler}
 */
export function auth(Ioptions: AuthOptions = {}): Middleware {
  const opts: AuthOptions = {
    useActiveDirectory: true,
    useGroups: true,
    useOwner: false,
    useCookies: true,
    groupFilterRegex: '.*',
    allowsGuest: false,
    allowsAnonymousLogon: false,
  };
  Object.assign(opts, options);
 
  let { credential, tsExpiry } = sspi.AcquireCredentialsHandle({
    packageName: 'Negotiate',
  });
 
  const checkCredentials = (): void => {
    Iif (tsExpiry < new Date()) {
      // renew server credentials
      sspi.FreeCredentialsHandle(credential);
      const renewed = sspi.AcquireCredentialsHandle({
        packageName: 'Negotiate',
      });
      credential = renewed.credential;
      tsExpiry = renewed.tsExpiry;
    }
  };
 
  const schManager = new ServerContextHandleManager(10000);
 
  // returns the node middleware.
  return (
    req: IncomingMessage,
    res: ServerResponse,
    next: NextFunction
  ): void => {
    (async (): Promise<void> => {
      try {
        const authorization = req.headers.authorization;
        if (!authorization) {
          debug('no authorization key in header');
          res.statusCode = 401;
          res.setHeader('WWW-Authenticate', 'Negotiate');
          return res.end();
        }
 
        Iif (!authorization.startsWith('Negotiate ')) {
          res.statusCode = 400;
          return res.end(`Malformed authentication token: ${authorization}`);
        }
 
        checkCredentials();
        const cookieToken = opts.useCookies
          ? schManager.initCookie(req, res)
          : undefined;
        debug('cookieToken: ', cookieToken);
 
        const token = authorization.substring('Negotiate '.length);
        const messageType = getMessageType(token);
        debug('messageType: ', messageType);
        const buffer = decode(token);
        debug(hexDump(buffer));
 
        // test if first token
        if (
          messageType === 'NTLM_NEGOTIATE_01' ||
          messageType === 'Kerberos_1'
        ) {
          await schManager.waitForReleased(cookieToken);
          debug('schManager waitForReleased finished.');
          const ssoMethod = messageType.startsWith('NTLM') ? 'NTLM' : 'Kerberos';
          schManager.setMethod(ssoMethod, cookieToken);
        }
 
        const input: AcceptSecurityContextInput = {
          credential,
          clientSecurityContext: {
            SecBufferDesc: {
              ulVersion: 0,
              buffers: [buffer],
            },
          },
        };
        const serverContextHandle = schManager.getServerContextHandle(
          cookieToken
        );
        if (serverContextHandle) {
          debug('adding to input a serverContextHandle (not first exchange)');
          input.contextHandle = serverContextHandle;
        }
        debug('input just before calling AcceptSecurityContext', input);
        const serverSecurityContext = sspi.AcceptSecurityContext(input);
        debug(
          'serverSecurityContext just after AcceptSecurityContext',
          serverSecurityContext
        );
        Iif (
          !['SEC_E_OK', 'SEC_I_CONTINUE_NEEDED'].includes(
            serverSecurityContext.SECURITY_STATUS
          )
        ) {
          // 'SEC_I_COMPLETE_AND_CONTINUE', 'SEC_I_COMPLETE_NEEDED' are considered as errors because it is used
          // only by 'Digest' SSP. (not by Negotiate, Kerberos or NTLM)
          throw new Error(
            'AcceptSecurityContext error: ' +
              serverSecurityContext.SECURITY_STATUS
          );
        }
        schManager.set(serverSecurityContext.contextHandle, cookieToken);
 
        debug('AcceptSecurityContext output buffer');
        debug(hexDump(serverSecurityContext.SecBufferDesc.buffers[0]));
 
        if (serverSecurityContext.SECURITY_STATUS === 'SEC_I_CONTINUE_NEEDED') {
          res.statusCode = 401;
          res.setHeader(
            'WWW-Authenticate',
            'Negotiate ' +
              encode(serverSecurityContext.SecBufferDesc.buffers[0])
          );
          return res.end();
        }
 
        const lastServerContextHandle = schManager.getServerContextHandle(
          cookieToken
        );
        const method = schManager.getMethod(cookieToken);
        const sso = new SSO(lastServerContextHandle, method);
        sso.setOptions(opts);
        await sso.load();
        req.sso = sso.getJSON();
        sspi.DeleteSecurityContext(lastServerContextHandle);
        schManager.release(cookieToken);
 
        // check if user is allowed.
        Iif (
          !opts.allowsAnonymousLogon &&
          req.sso.user.name === 'ANONYMOUS LOGON'
        ) {
          res.statusCode = 401;
          return res.end('Anonymous login not authorized.');
        }
        Iif (!opts.allowsGuest && req.sso.user.name === 'Guest') {
          res.statusCode = 401;
          return res.end('Guest not authorized.');
        }
 
        // user authenticated and allowed.
        res.setHeader(
          'WWW-Authenticate',
          'Negotiate ' + encode(serverSecurityContext.SecBufferDesc.buffers[0])
        );
        return next();
      } catch (e) {
        schManager.release();
        console.error(e);
        next(createError(400, `Error while doing SSO: ${e.message}`));
      }
    })();
  };
}