All files / src/sso auth.ts

79.09% Statements 87/110
74.24% Branches 49/66
100% Functions 4/4
78.3% Lines 83/106

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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 2311x 1x   1x   1x 1x 1x   1x 1x                 1x   1x                   4x 3x                   3x   3x       3x 4x                     3x             3x         9x 5x   5x 1x 1x 1x 1x     8x 8x 8x   8x     8x 8x 4x 4x 4x 4x     4x         4x 4x 4x 4x 4x 4x       6x     4x 2x 2x     2x     4x             4x 4x 2x 2x   4x       4x 4x 4x       4x                                           4x 4x   4x 4x 4x 2x 2x         2x     2x 2x     2x 2x 2x 4x 2x 2x 1x   1x 1x 1x     2x 2x     2x             2x           2x       2x                      
import createError from 'http-errors';
import { decode, encode } from 'base64-arraybuffer';
import { IncomingMessage, ServerResponse } from 'http';
import dbg from 'debug';
 
import { sspi, AcceptSecurityContextInput, CtxtHandle } from '../../lib/api';
import { hexDump, getMessageType } from './misc';
import { SSO } from './SSO';
import { ServerContextHandleManager } from './schm/ServerContextHandleManager';
import { SCHMWithCookies } from './schm/SCHMWithCookies';
import { SCHMWithSync } from './schm/SCHMWithSync';
import {
  AuthOptions,
  MessageType,
  Middleware,
  NextFunction,
  SSOMethod,
  SSOObject,
} from './interfaces';
import { getStatusInfo } from './status';
 
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(options: AuthOptions = {}): Middleware {
  const opts: AuthOptions = {
    useActiveDirectory: true,
    useGroups: true,
    useOwner: false,
    useCookies: true,
    groupFilterRegex: '.*',
    allowsGuest: false,
    allowsAnonymousLogon: false,
    useSession: 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: ServerContextHandleManager = opts.useCookies
    ? new SCHMWithCookies()
    : new SCHMWithSync(10000);
 
  let previousServerContextHandle: CtxtHandle;
 
  // returns the node middleware.
  return (
    req: IncomingMessage,
    res: ServerResponse,
    next: NextFunction
  ): void => {
    if (opts.useSession) {
      const session = ((req as unknown) as { session?: { sso: SSOObject } })
        .session;
      if (session?.sso) {
        session.sso.cached = true;
        req.sso = session.sso;
        next();
        return;
      }
    }
    (async (): Promise<void> => {
      const cookieToken = schManager.getCookieToken(req, res);
      debug('cookieToken: ', cookieToken);
 
      let messageType: MessageType = 'Unknown';
 
      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 token = authorization.substring('Negotiate '.length);
        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: SSOMethod = messageType.startsWith('NTLM')
            ? 'NTLM'
            : 'Kerberos';
          schManager.setMethod(ssoMethod, cookieToken);
        }
 
        const input: AcceptSecurityContextInput = {
          credential,
          SecBufferDesc: {
            ulVersion: 0,
            buffers: [buffer],
          },
        };
        const serverContextHandle = schManager.getHandle(cookieToken);
        if (serverContextHandle) {
          debug('adding to input a serverContextHandle (not first exchange)');
          input.contextHandle = serverContextHandle;
        }
        Iif (!serverContextHandle && messageType !== 'NTLM_NEGOTIATE_01') {
          debug('set cookie bug management');
          input.contextHandle = previousServerContextHandle;
        }
        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)
          if (serverSecurityContext.SECURITY_STATUS === 'SEC_E_LOGON_DENIED') {
            schManager.release(cookieToken);
            next(
              createError(
                401,
                `SEC_E_LOGON_DENIED. (incorrect login/password, or account disabled, or locked, etc.). Protocol Message = ${messageType}.`
              )
            );
            return;
          }
          throw new Error(
            'AcceptSecurityContext error: ' +
              serverSecurityContext.SECURITY_STATUS
          );
        }
        schManager.setHandle(serverSecurityContext.contextHandle, cookieToken);
        previousServerContextHandle = serverSecurityContext.contextHandle;
 
        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.getHandle(cookieToken);
        Iif (!lastServerContextHandle) {
          throw new Error('cannot get the server context handle');
        }
        const method = schManager.getMethod(cookieToken);
        const sso = new SSO(lastServerContextHandle, method);
        sso.setOptions(opts);
        await sso.load();
        req.sso = sso.getJSON();
        if (opts.useSession) {
          const session = ((req as unknown) as { session?: { sso: SSOObject } })
            .session;
          Eif (session) {
            req.sso.cached = false;
            session.sso = req.sso;
          }
        }
        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(cookieToken);
        console.error(e);
        console.error('statusInfo: ', getStatusInfo());
        console.error('messageType: ', messageType);
        next(createError(401, `Error while doing SSO: ${e.message}`));
      }
    })();
  };
}