Java源码示例:jcifs.smb.NtlmPasswordAuthentication
示例1
/**
* This method simply calls <tt>negotiate( req, resp, false )</tt>
* and then <tt>chain.doFilter</tt>. You can override and call
* negotiate manually to achive a variety of different behavior.
*/
@Override
public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
NtlmPasswordAuthentication ntlm;
if ( ( ntlm = negotiate(req, resp, false) ) == null ) {
return;
}
chain.doFilter(new NtlmHttpServletRequest(req, ntlm), response);
}
示例2
/**
* Performs NTLM authentication for the servlet request.
*
* @param tc
* context to use
*
* @param req
* The request being serviced.
* @param resp
* The response.
* @param challenge
* The domain controller challenge.
* @return credentials passed in the servlet request
* @throws IOException
* If an IO error occurs.
*/
public static NtlmPasswordAuthentication authenticate ( CIFSContext tc, HttpServletRequest req, HttpServletResponse resp, byte[] challenge )
throws IOException {
String msg = req.getHeader("Authorization");
if ( msg != null && msg.startsWith("NTLM ") ) {
byte[] src = Base64.decode(msg.substring(5));
if ( src[ 8 ] == 1 ) {
Type1Message type1 = new Type1Message(src);
Type2Message type2 = new Type2Message(tc, type1, challenge, null);
msg = new String(Base64.encode(type2.toByteArray()), "US-ASCII");
resp.setHeader("WWW-Authenticate", "NTLM " + msg);
}
else if ( src[ 8 ] == 3 ) {
Type3Message type3 = new Type3Message(src);
byte[] lmResponse = type3.getLMResponse();
if ( lmResponse == null )
lmResponse = new byte[0];
byte[] ntResponse = type3.getNTResponse();
if ( ntResponse == null )
ntResponse = new byte[0];
return new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge, lmResponse, ntResponse);
}
}
else {
resp.setHeader("WWW-Authenticate", "NTLM");
}
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
resp.setContentLength(0);
resp.flushBuffer();
return null;
}
示例3
/**
* This method simply calls <tt>negotiate( req, resp, false )</tt>
* and then <tt>chain.doFilter</tt>. You can override and call
* negotiate manually to achive a variety of different behavior.
*/
@Override
public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
NtlmPasswordAuthentication ntlm;
if ( ( ntlm = negotiate(req, resp, false) ) == null ) {
return;
}
chain.doFilter(new NtlmHttpServletRequest(req, ntlm), response);
}
示例4
/**
* Performs NTLM authentication for the servlet request.
*
* @param tc
* context to use
*
* @param req
* The request being serviced.
* @param resp
* The response.
* @param challenge
* The domain controller challenge.
* @return credentials passed in the servlet request
* @throws IOException
* If an IO error occurs.
*/
public static NtlmPasswordAuthentication authenticate ( CIFSContext tc, HttpServletRequest req, HttpServletResponse resp, byte[] challenge )
throws IOException {
String msg = req.getHeader("Authorization");
if ( msg != null && msg.startsWith("NTLM ") ) {
byte[] src = Base64.decode(msg.substring(5));
if ( src[ 8 ] == 1 ) {
Type1Message type1 = new Type1Message(src);
Type2Message type2 = new Type2Message(tc, type1, challenge, null);
msg = new String(Base64.encode(type2.toByteArray()), "US-ASCII");
resp.setHeader("WWW-Authenticate", "NTLM " + msg);
}
else if ( src[ 8 ] == 3 ) {
Type3Message type3 = new Type3Message(src);
byte[] lmResponse = type3.getLMResponse();
if ( lmResponse == null )
lmResponse = new byte[0];
byte[] ntResponse = type3.getNTResponse();
if ( ntResponse == null )
ntResponse = new byte[0];
return new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge, lmResponse, ntResponse);
}
}
else {
resp.setHeader("WWW-Authenticate", "NTLM");
}
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
resp.setContentLength(0);
resp.flushBuffer();
return null;
}
示例5
/**
* Creates a new instance of <code>SharedNamedPipe</code>.
*
* @param connection
* @throws IOException if the named pipe or its input or output streams do
* not open
* @throws UnknownHostException if host cannot be found for the named pipe
*/
public SharedNamedPipe(JtdsConnection connection) throws IOException {
super(connection.getBufferDir(), connection.getTdsVersion(), connection.getServerType());
// apply socketTimeout as responseTimeout
int timeout = connection.getSocketTimeout() * 1000;
String val = String.valueOf(timeout > 0 ? timeout : Integer.MAX_VALUE);
Config.setProperty("jcifs.smb.client.responseTimeout", val);
Config.setProperty("jcifs.smb.client.soTimeout", val);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
connection.getDomainName(), connection.getUser(), connection.getPassword());
StringBuilder url = new StringBuilder(32);
url.append("smb://");
url.append(connection.getServerName());
url.append("/IPC$");
final String instanceName = connection.getInstanceName();
if (instanceName != null && instanceName.length() != 0) {
if(!instanceName.startsWith("LOCALDB"))
url.append("/MSSQL$");
else
url.append("/");
url.append(instanceName);
}
String namedPipePath = DefaultProperties.getNamedPipePath(connection.getServerType(), instanceName);
url.append(namedPipePath);
setPipe(new SmbNamedPipe(url.toString(), SmbNamedPipe.PIPE_TYPE_RDWR, auth));
setOut(new DataOutputStream(getPipe().getNamedPipeOutputStream()));
final int bufferSize = Support.calculateNamedPipeBufferSize(
connection.getTdsVersion(), connection.getPacketSize());
setIn(new DataInputStream(
new BufferedInputStream(
getPipe().getNamedPipeInputStream(), bufferSize)));
}
示例6
public static List<SmbFile> getFilesFromDir(String path, NtlmPasswordAuthentication auth) throws Exception {
List<SmbFile> results = new ArrayList<SmbFile>();
Set<SmbFile> seen = new LinkedHashSet<SmbFile>();
Deque<SmbFile> queue = new ArrayDeque<SmbFile>();
SmbFile baseDir = new SmbFile(path, auth);
queue.add(baseDir);
while (!queue.isEmpty()) {
SmbFile file = queue.removeFirst();
seen.add(file);
if (file.isDirectory()) {
Set<SmbFile> smbFiles = new LinkedHashSet<SmbFile>();
Collections.addAll(smbFiles, file.listFiles());
for (SmbFile child : smbFiles) {
if (!seen.contains(child)) {
queue.add(child);
}
}
} else if (VideoUtils.isVideoFile(file.getName())) {
results.add(file);
}
}
return results;
}
示例7
public static List<SmbFile> getFiles(String user, String password, String path) {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", user, password);
List<SmbFile> files = Collections.emptyList();
try {
files = VideoUtils.getFilesFromDir(path, auth);
} catch (Exception e) {
e.printStackTrace();
}
return files;
}
示例8
@Override
public void configure() throws ConfigurationException {
if (getShare() == null)
throw new ConfigurationException("server share endpoint is required");
if (!getShare().startsWith("smb://"))
throw new ConfigurationException("attribute share must begin with [smb://]");
//Setup credentials if applied, may be null.
//NOTE: When using NtmlPasswordAuthentication without username it returns GUEST
CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
if (StringUtils.isNotEmpty(cf.getUsername())) {
auth = new NtlmPasswordAuthentication(getDomain(), cf.getUsername(), cf.getPassword());
log.debug("setting authentication to [" + auth.toString() + "]");
}
}
示例9
@Override
public URLConnection openConnection(URL url) throws IOException{
SingletonContext context = SingletonContext.getInstance();
NtlmPasswordAuthentication ntlmPasswordAuthentication =
new NtlmPasswordAuthentication(context, url.getUserInfo());
CIFSContext credentials =
SingletonContext.getInstance().withCredentials(ntlmPasswordAuthentication);
return new SmbFile(url, credentials);
}
示例10
@Override
protected final HandlerResult doAuthentication(
final Credential credential) throws GeneralSecurityException, PreventedException {
final SpnegoCredential ntlmCredential = (SpnegoCredential) credential;
final byte[] src = ntlmCredential.getInitToken();
UniAddress dc = null;
boolean success = false;
try {
if (this.loadBalance) {
// find the first dc that matches the includepattern
if (this.includePattern != null) {
final NbtAddress[] dcs= NbtAddress.getAllByName(this.domainController, NBT_ADDRESS_TYPE, null, null);
for (final NbtAddress dc2 : dcs) {
if(dc2.getHostAddress().matches(this.includePattern)){
dc = new UniAddress(dc2);
break;
}
}
} else {
dc = new UniAddress(NbtAddress.getByName(this.domainController, NBT_ADDRESS_TYPE, null));
}
} else {
dc = UniAddress.getByName(this.domainController, true);
}
final byte[] challenge = SmbSession.getChallenge(dc);
switch (src[NTLM_TOKEN_TYPE_FIELD_INDEX]) {
case NTLM_TOKEN_TYPE_ONE:
logger.debug("Type 1 received");
final Type1Message type1 = new Type1Message(src);
final Type2Message type2 = new Type2Message(type1,
challenge, null);
logger.debug("Type 2 returned. Setting next token.");
ntlmCredential.setNextToken(type2.toByteArray());
break;
case NTLM_TOKEN_TYPE_THREE:
logger.debug("Type 3 received");
final Type3Message type3 = new Type3Message(src);
final byte[] lmResponse = type3.getLMResponse() == null ? new byte[0] : type3.getLMResponse();
final byte[] ntResponse = type3.getNTResponse() == null ? new byte[0] : type3.getNTResponse();
final NtlmPasswordAuthentication ntlm = new NtlmPasswordAuthentication(
type3.getDomain(), type3.getUser(), challenge,
lmResponse, ntResponse);
logger.debug("Trying to authenticate {} with domain controller", type3.getUser());
try {
SmbSession.logon(dc, ntlm);
ntlmCredential.setPrincipal(this.principalFactory.createPrincipal(type3.getUser()));
success = true;
} catch (final SmbAuthException sae) {
throw new FailedLoginException(sae.getMessage());
}
break;
default:
logger.debug("Unknown type: {}", src[NTLM_TOKEN_TYPE_FIELD_INDEX]);
}
} catch (final Exception e) {
throw new FailedLoginException(e.getMessage());
}
if (!success) {
throw new FailedLoginException();
}
return new DefaultHandlerResult(this, new BasicCredentialMetaData(ntlmCredential), ntlmCredential.getPrincipal());
}
示例11
@Override
protected final HandlerResult doAuthentication(
final Credential credential) throws GeneralSecurityException, PreventedException {
final SpnegoCredential ntlmCredential = (SpnegoCredential) credential;
final byte[] src = ntlmCredential.getInitToken();
UniAddress dc = null;
boolean success = false;
try {
if (this.loadBalance) {
// find the first dc that matches the includepattern
if(this.includePattern != null){
NbtAddress [] dcs = NbtAddress.getAllByName(this.domainController, 0x1C, null, null);
for (NbtAddress dc2 : dcs) {
if(dc2.getHostAddress().matches(this.includePattern)){
dc = new UniAddress(dc2);
break;
}
}
} else {
dc = new UniAddress(NbtAddress.getByName(this.domainController,
0x1C, null));
}
} else {
dc = UniAddress.getByName(this.domainController, true);
}
final byte[] challenge = SmbSession.getChallenge(dc);
switch (src[8]) {
case 1:
logger.debug("Type 1 received");
final Type1Message type1 = new Type1Message(src);
final Type2Message type2 = new Type2Message(type1,
challenge, null);
logger.debug("Type 2 returned. Setting next token.");
ntlmCredential.setNextToken(type2.toByteArray());
case 3:
logger.debug("Type 3 received");
final Type3Message type3 = new Type3Message(src);
final byte[] lmResponse = type3.getLMResponse() == null ? new byte[0] : type3.getLMResponse();
byte[] ntResponse = type3.getNTResponse() == null ? new byte[0] : type3.getNTResponse();
final NtlmPasswordAuthentication ntlm = new NtlmPasswordAuthentication(
type3.getDomain(), type3.getUser(), challenge,
lmResponse, ntResponse);
logger.debug("Trying to authenticate {} with domain controller", type3.getUser());
try {
SmbSession.logon(dc, ntlm);
ntlmCredential.setPrincipal(new SimplePrincipal(type3.getUser()));
success = true;
} catch (final SmbAuthException sae) {
throw new FailedLoginException(sae.getMessage());
}
default:
logger.debug("Unknown type: {}", src[8]);
}
} catch (final Exception e) {
throw new FailedLoginException(e.getMessage());
}
if (!success) {
throw new FailedLoginException();
}
return new HandlerResult(this, new BasicCredentialMetaData(ntlmCredential), ntlmCredential.getPrincipal());
}
示例12
public void bind(BindInterceptorChain chain, DistinguishedName dn,
Password pwd, LDAPConstraints constraints) throws LDAPException {
Vector<RDN> rdns = dn.getDN().getRDNs();
String domain = rdns.get(1).getValue();
String user = rdns.get(0).getValue();
try {
SmbSession.logon(this.addr,new NtlmPasswordAuthentication(domain,user,new String(pwd.getValue())));
} catch (SmbException e) {
e.printStackTrace();
throw new LDAPException(e.toString(),LDAPException.INVALID_CREDENTIALS,"");
}
chain.getSession().put(SessionVariables.BOUND_INTERCEPTORS,this.name);
}
示例13
public void bind(BindInterceptorChain chain, DistinguishedName dn,
Password pwd, LDAPConstraints constraints) throws LDAPException {
Vector<RDN> rdns = dn.getDN().getRDNs();
String domain = rdns.get(1).getValue();
String user = rdns.get(0).getValue();
try {
SmbSession.logon(this.addr,new NtlmPasswordAuthentication(domain,user,new String(pwd.getValue())));
} catch (SmbException e) {
e.printStackTrace();
throw new LDAPException(e.toString(),LDAPException.INVALID_CREDENTIALS,"");
}
chain.getSession().put(SessionVariables.BOUND_INTERCEPTORS,this.name);
}
示例14
@Override
public void setUp() throws ConfigurationException, IOException, FileSystemException {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, username, password);
context = new SmbFile(share, auth);
}
示例15
@Override
public void configure() throws ConfigurationException {
super.configure();
if (getShare() == null)
throw new ConfigurationException(getLogPrefix() + "server share endpoint is required");
if (!getShare().startsWith("smb://"))
throw new ConfigurationException(getLogPrefix() + "url must begin with [smb://]");
if (getAction() == null)
throw new ConfigurationException(getLogPrefix() + "action must be specified");
if (!actions.contains(getAction()))
throw new ConfigurationException(getLogPrefix() + "unknown or invalid action ["
+ getAction() + "] supported actions are " + actions.toString() + "");
//Check if necessarily parameters are available
ParameterList parameterList = getParameterList();
if (getAction().equals("upload")
&& (parameterList == null || parameterList.findParameter("file") == null))
throw new ConfigurationException(getLogPrefix()
+ "the upload action requires the file parameter to be present");
if (getAction().equals("rename")
&& (parameterList == null || parameterList.findParameter("destination") == null))
throw new ConfigurationException(getLogPrefix()
+ "the rename action requires a destination parameter to be present");
//Setup credentials if applied, may be null.
//NOTE: When using NtmlPasswordAuthentication without username it returns GUEST
CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
if (StringUtils.isNotEmpty(cf.getUsername())) {
auth = new NtlmPasswordAuthentication(getAuthDomain(), cf.getUsername(),
cf.getPassword());
log.debug("setting authentication to [" + auth.toString() + "]");
}
try {
//Try to initially connect to the host and create the SMB session.
//The session automatically closes and re-creates when required.
smbContext = new SmbFile(getShare(), auth);
} catch (MalformedURLException e) {
throw new ConfigurationException(e);
}
}
示例16
/**
* Calls the static {@link #authenticate(CIFSContext, HttpServletRequest,
* HttpServletResponse, byte[])} method to perform NTLM authentication
* for the specified servlet request.
*
* @param tc
*
* @param req
* The request being serviced.
* @param resp
* The response.
* @param challenge
* The domain controller challenge.
* @return credentials passed in the servlet request
* @throws IOException
* If an IO error occurs.
*/
public NtlmPasswordAuthentication doAuthentication ( CIFSContext tc, HttpServletRequest req, HttpServletResponse resp, byte[] challenge )
throws IOException {
return authenticate(tc, req, resp, challenge);
}
示例17
/**
* Calls the static {@link #authenticate(CIFSContext, HttpServletRequest,
* HttpServletResponse, byte[])} method to perform NTLM authentication
* for the specified servlet request.
*
* @param tc
*
* @param req
* The request being serviced.
* @param resp
* The response.
* @param challenge
* The domain controller challenge.
* @return credentials passed in the servlet request
* @throws IOException
* If an IO error occurs.
*/
public NtlmPasswordAuthentication doAuthentication ( CIFSContext tc, HttpServletRequest req, HttpServletResponse resp, byte[] challenge )
throws IOException {
return authenticate(tc, req, resp, challenge);
}