Commit f87039c1 authored by Benjamin Chelli's avatar Benjamin Chelli

Initial commit

parents
.DS_Store
node_modules
test.js
# SMB2 Client for Node.js
## Introduction
This library is a simple implementation of SMB2 for Node.js. It allows you to access a SMB2 share as if you were using the native fs library.
The development is still at an experimental stage and should not be yet considered for production environment.
## Installation
npm install smb2
## Usage
```javascript
// load the library
var SMB2 = require('smb2');
// create an SMB2 instance
var s = new SMB2({
share:'\\\\000.000.000.000\\c$'
, domain:'DOMAIN'
, username:'username'
, password:'password!'
});
// negotiate the connection with the server
s.connect(function(err){
// if an error happen => throw it
if(err) throw err;
// read the content of the folder
s.readDir('Windows\\System32', function(err, files){
// if an error happen => throw it
if(err) throw err;
// display content in the console
console.log(files.map(function(v){return v.Filename}));
// close the connection
s.close();
});
});
```
## References
The[MS-SMB2]: Server Message Block (SMB) Protocol Versions 2 and 3
Copyright (C) 2014 Microsoft
http://msdn.microsoft.com/en-us/library/cc246482.aspx
## License
(The MIT License)
Copyright (c) 2013-2014 Benjamin Chelli <benjamin@chelli.net>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
/*
* STATICS
*/
var messageId = 0;
/*
* CONSTANTS
*/
const protocolId = new Buffer([0xFE, 'S'.charCodeAt(0), 'M'.charCodeAt(0), 'B'.charCodeAt(0)])
, processId = new Buffer([0xFF, 0xFE, 0x00, 0x00])
, headerTranslates = {
'Command': {
'NEGOTIATE': 0x0000
, 'SESSION_SETUP': 0x0001
, 'LOGOFF': 0x0002
, 'TREE_CONNECT': 0x0003
, 'TREE_DISCONNECT': 0x0004
, 'CREATE': 0x0005
, 'CLOSE': 0x0006
, 'FLUSH': 0x0007
, 'READ': 0x0008
, 'WRITE': 0x0009
, 'LOCK': 0x000A
, 'IOCTL': 0x000B
, 'CANCEL': 0x000C
, 'ECHO': 0x000D
, 'QUERY_DIRECTORY': 0x000E
, 'CHANGE_NOTIFY': 0x000F
, 'QUERY_INFO': 0x0010
, 'SET_INFO': 0x0011
, 'OPLOCK_BREAK': 0x0012
}
}
, flags = {
'SERVER_TO_REDIR': 0x00000001
, 'ASYNC_COMMAND': 0x00000002
, 'RELATED_OPERATIONS': 0x00000004
, 'SIGNED': 0x00000008
, 'DFS_OPERATIONS': 0x10000000
, 'REPLAY_OPERATION': 0x20000000
}
, headerLength = 64
, headerSync = [
['ProtocolId',4,protocolId]
, ['StructureSize',2,headerLength]
, ['CreditCharge',2,0]
, ['Status',4,0]
, ['Command',2]
, ['Credit',2,126]
, ['Flags',4,0]
, ['NextCommand',4,0]
, ['MessageId',4]
, ['MessageIdHigh',4,0]
, ['ProcessId',4,processId]
, ['TreeId',4,0]
, ['SessionId',8,0]
, ['Signature',16,0]
]
, headerASync = [
['ProtocolId',4,protocolId]
, ['StructureSize',2,headerLength]
, ['CreditCharge',2,0]
, ['Status',4,0]
, ['Command',2]
, ['Credit',2,126]
, ['Flags',4,0]
, ['NextCommand',4,0]
, ['MessageId',4]
, ['MessageIdHigh',4,0]
, ['AsyncId',8]
, ['SessionId',8,0]
, ['Signature',16,0]
]
;
/*
* CONSTRUCTOR
*/
var SMB2Message = module.exports = function(options){
// INIT HEADERS
this.headers = {};
if(options && options.headers){
this.setHeaders(options.headers);
}
// INIT REQUEST
this.request = {};
if(options && options.request){
this.setRequest(options.request);
}
// INIT RESPONSE
this.response = {};
}
var proto = SMB2Message.prototype = {};
proto.setHeaders = function(obj){
for(var key in obj){
this.headers[key] = obj[key];
}
this.structure = require('./structures/'+this.headers['Command'].toLowerCase());
}
proto.getHeaders = function(){
return this.headers;
}
proto.setRequest = function(request){
this.request = request;
}
proto.getResponse = function(){
return this.response;
}
proto.getBuffer = function(){
var buffer = new Buffer(0xFFFF)
, length = 0
;
// SET MESSAGE ID
if(!this.isMessageIdSetted){
this.isMessageIdSetted = true;
this.headers['MessageId'] = messageId++;
}
// HEADERS
length += writeHeaders(this, buffer);
// REQUEST
length += writeRequest(this, buffer, headerLength)
// extract the data
var output = new Buffer(length);
buffer.copy(output, 0, 0, length);
return output;
}
proto.parseBuffer = function(buffer){
// HEADERS
readHeaders(this, buffer)
// RESPONSE
readResponse(this, buffer, headerLength)
}
/*
* HELPERS
*/
function dataToBuffer(data, length) {
// buffers will be buffers
if(Buffer.isBuffer(data)){
return data;
}
// string to buffer
if(typeof data == 'string'){
return new Buffer(data);
}
// raw data to buffer
var result = new Buffer(length);
for(var i=0; i<length;i++){
result.writeUInt8(
0xFF & (data >> (i*8))
, i
);
}
return result;
}
function bufferToData(buffer) {
// not a buffer go away
if(!Buffer.isBuffer(buffer)){
return buffer;
}
// raw data to buffer
var result = 0;
for(var i=0; i<buffer.length;i++){
result += buffer.readUInt8(i) << (i*8);
}
return result;
}
function writeData(buffer, data, offset, length){
dataToBuffer(data, length).copy(buffer, offset, 0)
}
function readData(buffer, offset, length){
return buffer.slice(offset, offset+length);
}
function translate(key, value){
if(headerTranslates[key] && typeof headerTranslates[key][value] != 'undefined'){
return headerTranslates[key][value];
}
return value;
}
function unTranslate(key, value){
if(headerTranslates[key]){
for(var t in headerTranslates[key]){
if(headerTranslates[key][t] == value){
return t;
}
}
}
return null;
}
/*
* PRIVATE FUNCTIONS
*/
function readHeaders(message, buffer){
var header = message.isAsync ? headerASync : headerSync
, offset = 0
;
for(var i in header){
var key = header[i][0]
, length = header[i][1]
;
message.headers[key] = readData(
buffer
, offset
, length
);
if(length <= 8){
message.headers[key] = unTranslate(key, bufferToData(message.headers[key])) || message.headers[key];
}
offset += length;
}
message.structure = require('./structures/'+message.headers['Command'].toLowerCase());
}
function writeHeaders(message, buffer){
var header = message.isAsync ? headerASync : headerSync
, offset = 0
;
for(var i in header){
var key = header[i][0]
, length = header[i][1]
, defaultValue = header[i][2] || 0
;
writeData(
buffer
, translate(key, message.headers[key] || defaultValue)
, offset
, length
);
offset += length;
}
return offset;
}
function readResponse(message, buffer, offset){
for(var i in message.structure.response){
var key = message.structure.response[i][0]
, length = message.structure.response[i][1] || 1
;
if(typeof length == 'string'){
length = bufferToData(message.response[length]);
}
message.response[key] = readData(buffer, offset, length);
offset += length;
}
}
function writeRequest(message, buffer, offset){
var initOffset = offset
, needsRewrite = false
, tmpBuffer = new Buffer(buffer.length)
;
offset = 0;
for(var i in message.structure.request){
var key = message.structure.request[i][0]
, length = message.structure.request[i][1] || 1
, defaultValue = message.structure.request[i][2] || 0
;
if(typeof length == 'string'){
message.request[key] = message.request[key] || '';
if(message.request[length] != message.request[key].length) {
message.request[length] = message.request[key].length;
needsRewrite = true;
}
length = message.request[key].length;
} else {
message.request[key] = message.request[key] || defaultValue;
}
writeData(
tmpBuffer
, message.request[key]
, offset
, length
);
offset += length;
}
if(needsRewrite){
writeRequest(message, tmpBuffer, 0);
}
tmpBuffer.copy(buffer, initOffset, 0, offset);
return offset;
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, params){
return new SMB2Message({
headers:{
'Command':'CLOSE'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'FileId':params.FileId
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(null);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, params){
var buffer = new Buffer(params.path, 'ucs2');
return new SMB2Message({
headers:{
'Command':'CREATE'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'Buffer':buffer
, 'DesiredAccess':0x001701DF
, 'FileAttributes':0x00000080
, 'ShareAccess':0x00000000
, 'CreateDisposition':0x00000005
, 'CreateOptions':0x00000044
, 'NameOffset':0x0078
, 'CreateContextsOffset':0x007A+buffer.length
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(null, response.getResponse());
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection){
return new SMB2Message({
headers:{
'Command':'NEGOTIATE'
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(null);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, params){
var buffer = new Buffer(params.path, 'ucs2');
return new SMB2Message({
headers:{
'Command':'CREATE'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'Buffer':buffer
, 'NameOffset':0x0078
, 'CreateContextsOffset':0x007A+buffer.length
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(null, response.getResponse());
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, params){
return new SMB2Message({
headers:{
'Command':'QUERY_DIRECTORY'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'FileId':params.FileId
, 'Buffer':new Buffer('*', 'ucs2')
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(
null
, parseFiles(response.getResponse().Buffer)
);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
/*
* HELPERS
*/
function parseFiles(buffer){
var files = []
, offset = 0
, nextFileOffset = -1
;
while(nextFileOffset!=0){
// extract next file offset
nextFileOffset = buffer.readUInt32LE(offset);
// extract the file
files.push(
parseFile(
buffer.slice(offset+4, nextFileOffset ? offset+nextFileOffset : buffer.length)
)
);
// move to nex file
offset += nextFileOffset;
}
return files;
}
function parseFile(buffer){
var file = {}
, offset = 0
;
// index
file.Index = buffer.readUInt32LE(offset);
offset+=4;
// CreationTime
file.CreationTime = buffer.slice(offset, offset+8);
offset+=8;
// LastAccessTime
file.LastAccessTime = buffer.slice(offset, offset+8);
offset+=8;
// LastWriteTime
file.LastWriteTime = buffer.slice(offset, offset+8);
offset+=8;
// ChangeTime
file.ChangeTime = buffer.slice(offset, offset+8);
offset+=8;
// EndofFile
file.EndofFile = buffer.slice(offset, offset+8);
offset+=8;
// AllocationSize
file.AllocationSize = buffer.slice(offset, offset+8);
offset+=8;
// FileAttributes
file.FileAttributes = buffer.readUInt32LE(offset);
offset+=4;
// FilenameLength
file.FilenameLength = buffer.readUInt32LE(offset);
offset+=4;
// EASize
file.EASize = buffer.readUInt32LE(offset);
offset+=4;
// ShortNameLength
file.ShortNameLength = buffer.readUInt8(offset);
offset+=1;
// FileId
file.FileId = buffer.slice(offset, offset+8);
offset+=8;
// Reserved
offset+=27;
// Filename
file.Filename = buffer.slice(offset, offset+file.FilenameLength).toString('ucs2');
offset+=file.FilenameLength;
return file;
}
\ No newline at end of file
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, file){
return new SMB2Message({
headers:{
'Command':'READ'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'FileId':file.FileId
, 'Length':file.Length
, 'Offset':file.Offset
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if (err.code == 'STATUS_SUCCESS'){
cb && cb(null, response.getResponse().Buffer);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
, ntlm = require('ntlm')
;
module.exports = {
generate:function(connection){
return new SMB2Message({
headers:{
'Command':'SESSION_SETUP'
}
, request:{
'Buffer':ntlm.encodeType1(
connection.ip
, connection.domain
)
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_MORE_PROCESSING_REQUIRED'){
connection.SessionId = h.SessionId;
connection.nonce = ntlm.decodeType2(response.getResponse().Buffer);
cb && cb(null);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
, ntlm = require('ntlm')
;
module.exports = {
generate:function(connection){
return new SMB2Message({
headers:{
'Command':'SESSION_SETUP'
, 'SessionId':connection.SessionId
}
, request:{
'Buffer':ntlm.encodeType3(
connection.username
, connection.ip
, connection.domain
, connection.nonce
, connection.password
)
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if( err.code == 'STATUS_LOGON_FAILURE'){
cb && cb(new Error('Login attempt fail'));
} else if(err.code == 'STATUS_SUCCESS'){
cb && cb(null);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
var fileInfoClasses = {
'FileAllocationInformation': 19
, 'FileBasicInformation': 4
, 'FileDispositionInformation': 13
, 'FileEndOfFileInformation': 20
, 'FileFullEaInformation': 15
, 'FileLinkInformation': 11
, 'FileModeInformation': 16
, 'FilePipeInformation': 23
, 'FilePositionInformation': 14
, 'FileRenameInformation': 10
, 'FileShortNameInformation': 40
, 'FileValidDataLengthInformation': 39
};
module.exports = {
generate:function(connection, params){
return new SMB2Message({
headers:{
'Command':'SET_INFO'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'FileInfoClass':fileInfoClasses[params.FileInfoClass]
, 'FileId':params.FileId
, 'Buffer':params.Buffer
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
cb && cb(null, response.getResponse());
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection){
return new SMB2Message({
headers:{
'Command':'TREE_CONNECT'
, 'SessionId':connection.SessionId
}
, request:{
'Buffer':new Buffer(connection.fullPath, 'ucs2')
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if(err.code == 'STATUS_SUCCESS'){
connection.TreeId = h.TreeId;
cb && cb(null);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
var SMB2Message = require('../message')
, MsErref = require('../tools/ms_erref')
, bigint = require('../tools/bigint')
;
module.exports = {
generate:function(connection, params){
return new SMB2Message({
headers:{
'Command':'WRITE'
, 'SessionId':connection.SessionId
, 'TreeId':connection.TreeId
}
, request:{
'FileId':params.FileId
, 'Offset':params.Offset
, 'Buffer':params.Buffer
}
})
}
, parse:function(connection, cb){
return function(response){
var h = response.getHeaders()
, err = MsErref.getStatus(bigint.fromBuffer(h.Status).toNumber())
;
if (err.code == 'STATUS_SUCCESS'){
cb && cb(null, response.getResponse().Buffer);
} else {
cb && cb(new Error(MsErref.getErrorMessage(err)));
}
}
}
}
/*
* CONSTANTS
*/
var shareRegExp = /\\\\([^\\]*)\\([^\\]*)\\?/
, port = 445
;
/*
* DEPENDENCIES
*/
var net = require('net')
, bigint = require('./tools/bigint')
, SMB2Message = require('./message')
, fs = require('fs')
;
/*
* CONSTRUCTOR
*/
var SMB = module.exports = function(opt){
opt = opt || {};
// Parse share-string
var matches;
if(!opt.share || !(matches = opt.share.match(shareRegExp))){
throw new Error('the share is not valid');
}
// resolve IP from NetBios
// this.ip = netBios.resolve(matches[0]);
this.ip = matches[1];
// extract share
this.share = matches[2];
// save the full path
this.fullPath = opt.share;
// packet concurrency
this.packetConcurrency = opt.packetConcurrency || 20;
// store authentification
this.domain = opt.domain;
this.username = opt.username;
this.password = opt.password;
// set session id
this.SessionId = 0;
// create a socket
this.socket = new net.Socket({
allowHalfOpen:true
});
// attach data events to socket
this.socket.on('data', parseResponse(this));
var connection = this;
this.socket.on('error', function(){
if(connection.debug){
console.log('-- error');
console.log(arguments);
}
});
};
/*
* PROTOTYPE
*/
var proto = SMB.prototype = {};
/*
* connect
* =======
*
* connect you to the SMB2 server:
*
* - open TCP socket
*
* - negotiation SM2 connection
*
* - setup session / ntlm negotiatiation
*
* - setup session / ntlm authetication
*
* - tree connect
*
*/
proto.connect = function(cb){
var connection = this;
// open TCP socket
connection.socket.connect(port, this.ip);
// SMB2 negotiate connection
SMB2Request('negotiate', {}, connection, function(err){
if(err) cb && cb(err);
// SMB2 setup session / negotiate ntlm
else SMB2Request('session_setup_step1', {}, connection, function(err){
if(err) cb && cb(err);
// SMB2 setup session / autheticate with ntlm
else SMB2Request('session_setup_step2', {}, connection, function(err){
if(err) cb && cb(err);
// SMB2 tree connect
else SMB2Request('tree_connect', {}, connection, function(err){
if(err) cb && cb(err);
else cb && cb(null);
});
});
});
});
}
/*
* close
* =====
*
* close your connection to the SMB2 server
*
* - close TCP connection
*
*/
proto.close = function(){
this.socket.end();
}
/*
* readDir
* =======
*
* list the file / directory from the path provided:
*
* - open the directory
*
* - query directory content
*
* - close the directory
*
*/
proto.readDir = function(path, cb){
var connection = this;
// SMB2 open directory
SMB2Request('open', {path:path}, connection, function(err, file){
if(err) cb && cb(err);
// SMB2 query directory
else SMB2Request('query_directory', file, connection, function(err, files){
if(err) cb && cb(err);
// SMB2 close directory
else SMB2Request('close', file, connection, function(err){
cb && cb(err, files);
});
});
});
}
/*
* readFile
* ========
*
* read the content of a file from the share
*
* - open the file
*
* - read the content
*
* - close the file
*
*/
proto.readFile = function(path, cb){
var connection = this;
// SMB2 open file
SMB2Request('open', {path:dest}, connection, function(err, file){
if(err) cb && cb(err);
// SMB2 read file content
else {
var fileLength = 0
, offset = new bigint(8)
, stop = false
, nbRemainingPackets = 0
, maxPacketSize = 0x00010000
;
// get file length
for(var i=0;i<file.EndofFile.length;i++){
fileLength |= file.EndofFile[i] << (i*8);
}
var result = new Buffer(fileLength);
// callback manager
function callback(offset){
return function(err, content){
if(stop) return;
if(err) {
cb && cb(err);
stop = true;
} else {
content.copy(result, offset.toNumber());
nbRemainingPackets--;
checkDone();
}
}
}
// callback manager
function checkDone(){
if(stop) return;
createPackets();
if(nbRemainingPackets==0 && offset.ge(fileLength)) {
SMB2Request('close', file, connection, function(err){
cb && cb(err, result);
})
}
}
// create packets
function createPackets(){
while(nbRemainingPackets<connection.packetConcurrency && offset.lt(fileLength)){
// process packet size
var rest = offset.sub(fileLength).neg();
var packetSize = rest.gt(maxPacketSize) ? maxPacketSize : rest.toNumber();
// generate buffer
SMB2Request('read', {
'FileId':file.FileId
, 'Length':packetSize
, 'Offset':offset.toBuffer()
}, connection, callback(offset));
offset = offset.add(packetSize);
nbRemainingPackets++;
}
}
checkDone();
}
});
}
/*
* writeFile
* =========
*
* create and write file on the share
*
* - create the file
*
* - set info of the file
*
* - set content of the file
*
* - close the file
*
*/
proto.writeFile = function(src, dest, cb){
var connection = this
, file
, fileContent
, fileLength
;
function createFile(fileCreated){
SMB2Request('create', {path:dest}, connection, function(err, f){
if(err) cb && cb(err);
// SMB2 set file size
else {
file = f;
fileCreated();
}
});
}
function closeFile(fileClosed){
SMB2Request('close', file, connection, function(err){
if(err) cb && cb(err);
else {
file = null;
fileClosed();
}
});
}
function openFile(fileOpened){
SMB2Request('open', {path:dest}, connection, function(err, f){
if(err) cb && cb(err);
// SMB2 read file content
else {
file = f;
fileOpened();
}
});
}
function openSrcFile(fileOpened){
fileContent = fs.readFileSync(src);
fileLength = new bigint(8, fileContent.length);
fileOpened();
}
function setFileSize(fileSizeSetted){
SMB2Request('set_info', {FileId:file.FileId, FileInfoClass:'FileEndOfFileInformation', Buffer:fileLength.toBuffer()}, connection, function(err){
if(err) cb && cb(err);
else fileSizeSetted();
});
}
function writeFile(fileWritten){
var offset = new bigint(8)
, stop = false
, nbRemainingPackets = 0
, maxPacketSize = new bigint(8, 0x00010000 - 0x71)
;
// callback manager
function callback(offset){
return function(err){
if(stop) return;
if(err) {
cb && cb(err);
stop = true;
} else {
nbRemainingPackets--;
checkDone();
}
}
}
// callback manager
function checkDone(){
if(stop) return;
createPackets();
if(nbRemainingPackets==0 && offset.ge(fileLength)) {
fileWritten();
}
}
// create packets
function createPackets(){
while(nbRemainingPackets<connection.packetConcurrency && offset.lt(fileLength)){
// process packet size
var rest = fileLength.sub(offset);
var packetSize = rest.gt(maxPacketSize) ? maxPacketSize : rest;
// generate buffer
SMB2Request('write', {
'FileId':file.FileId
, 'Offset':offset.toBuffer()
, 'Buffer':fileContent.slice(offset.toNumber(), offset.add(packetSize).toNumber())
}, connection, callback(offset));
offset = offset.add(packetSize);
nbRemainingPackets++;
}
}
checkDone();
}
this.fileExists(dest, function(err, exists){
if(err) cb && cb(err);
else if(!exists){
createFile(function(){
openSrcFile(function(){
setFileSize(function(){
writeFile(function(){
closeFile(cb);
});
});
});
});
} else {
cb(new Error('File already exists'));
}
});
}
/*
* fileExists
* =========
*
* test the existence of a file
*
* - try to open the file
*
* - close the file
*
*/
proto.fileExists = function(path, cb){
var connection = this;
SMB2Request('open', {path:path}, connection, function(err, file){
if(err) cb && cb(null, false);
else SMB2Request('close', file, connection, function(err){
cb && cb(null, true);
});
});
}
/*
* unlinkFile
* ==========
*
* remove file:
*
* - open the file
*
* - remove the file
*
* - close the file
*
*/
proto.unlinkFile = function(path, cb){
var connection = this;
this.fileExists(path, function(err, exists){
if(err) cb && cb(err);
else if(exists){
// SMB2 open file
SMB2Request('create', {path:path}, connection, function(err, file){
if(err) cb && cb(err);
// SMB2 query directory
else SMB2Request('set_info', {FileId:file.FileId, FileInfoClass:'FileDispositionInformation',Buffer:(new bigint(1,1)).toBuffer()}, connection, function(err, files){
if(err) cb && cb(err);
// SMB2 close directory
else SMB2Request('close', file, connection, function(err){
cb && cb(err, files);
});
});
});
} else {
cb(new Error('File does not exists'));
}
});
}
/*
* MESSAGE MANAGMENT
*/
function SMB2Request(messageName, params, connection, cb){
var msg = require('./messages/'+messageName)
, smbMessage = msg.generate(connection, params)
;
// send
sendNetBiosMessage(
connection
, smbMessage
);
// wait for the response
getResponse(
connection
, smbMessage.getHeaders().MessageId
, msg.parse(connection, cb)
);
}
function sendNetBiosMessage(connection, message) {
var smbRequest = message.getBuffer();
if(connection.debug){
console.log('--request');
console.log(smbRequest.toString('hex'));
}
// create NetBios package
var buffer = new Buffer(smbRequest.length+4);
// write NetBios cmd
buffer.writeUInt8(0x00, 0);
// write message length
buffer.writeUInt8((0xFF0000 & smbRequest.length) >> 16, 1);
buffer.writeUInt16BE(0xFFFF & smbRequest.length, 2);
// write message content
smbRequest.copy(buffer, 4, 0, smbRequest.length);
// Send it !!!
connection.newResponse = false;
connection.socket.write(buffer);
return true;
}
function parseResponse(c){
c.responses = {};
c.responsesCB = {};
c.responseBuffer = new Buffer(0);
return function(response){
// concat new response
c.responseBuffer = Buffer.concat([c.responseBuffer, response]);
// extract complete messages
var extract = true;
while(extract){
extract = false;
// has a message header
if(c.responseBuffer.length >= 4) {
// message is complete
var msgLength = (c.responseBuffer.readUInt8(1) << 16) + c.responseBuffer.readUInt16BE(2);
if(c.responseBuffer.length >= msgLength + 4) {
// set the flags
extract = true;
// parse message
var r = c.responseBuffer.slice(4, msgLength+4)
, message = new SMB2Message()
;
message.parseBuffer(r);
//debug
if(c.debug){
console.log('--response');
console.log(r.toString('hex'));
}
// get the message id
var mId = message.getHeaders().MessageId.toString('hex');
// check if the message can be dispatched
// or store it
if(c.responsesCB[mId]) {
c.responsesCB[mId](message);
delete c.responsesCB[mId];
} else {
c.responses[mId] = message;
}
// remove from response buffer
c.responseBuffer = c.responseBuffer.slice(msgLength+4);
}
}
}
}
}
function getResponse(c, mId, cb) {
var messageId = new Buffer(4);
messageId.writeUInt32LE(mId, 0);
messageId = messageId.toString('hex');
if(c.responses[messageId]) {
cb(c.responses[messageId]);
delete c.responses[messageId];
} else {
c.responsesCB[messageId] = cb;
}
}
module.exports = {
request:[
['StructureSize', 2, 24]
, ['Flags', 2, 0]
, ['Reserved', 4, 0]
, ['FileId', 16]
]
, response:[
['StructureSize', 2]
, ['Flags', 2]
, ['Reserved', 4]
, ['CreationTime', 8]
, ['LastAccessTime', 8]
, ['LastWriteTime', 8]
, ['ChangeTime', 8]
, ['AllocationSize', 8]
, ['EndofFile', 8]
, ['FileAttributes', 4]
]
}
module.exports = {
request:[
['StructureSize', 2, 57]
, ['SecurityFlags', 1, 0]
, ['RequestedOplockLevel', 1, 0]
, ['ImpersonationLevel', 4, 0x00000002]
, ['SmbCreateFlags', 8, 0]
, ['Reserved', 8, 0]
, ['DesiredAccess', 4, 0x00100081]
, ['FileAttributes', 4, 0x00000000]
, ['ShareAccess', 4, 0x00000007]
, ['CreateDisposition', 4, 0x00000001]
, ['CreateOptions', 4, 0x00000020]
, ['NameOffset', 2]
, ['NameLength', 2]
, ['CreateContextsOffset', 4]
, ['CreateContextsLength', 4]
, ['Buffer', 'NameLength']
, ['Reserved2', 2, 0x4200]
, ['CreateContexts', 'CreateContextsLength', '']
]
, response:[
['StructureSize', 2]
, ['OplockLevel', 1]
, ['Flags', 1]
, ['CreateAction', 4]
, ['CreationTime', 8]
, ['LastAccessTime', 8]
, ['LastWriteTime', 8]
, ['ChangeTime', 8]
, ['AllocationSize', 8]
, ['EndofFile', 8]
, ['FileAttributes', 4]
, ['Reserved2', 4]
, ['FileId', 16]
, ['CreateContextsOffset', 4]
, ['CreateContextsLength', 4]
, ['Buffer', 'CreateContextsLength']
]
}
module.exports = {
request:[
['StructureSize', 2, 36]
, ['DialectCount', 2, 2]
, ['SecurityMode', 2, 1]
, ['Reserved', 2, 0]
, ['Capabilities', 4, 0]
, ['ClientGuid', 16, 0]
, ['ClientStartTime', 8, 0]
, ['Dialects', 4, new Buffer([0x02,0x02,0x10,0x02])]
]
, response:[
['StructureSize', 2]
, ['SecurityMode', 2]
, ['DialectRevision', 2]
, ['Reserved', 2]
, ['ServerGuid', 16]
, ['Capabilities', 4]
, ['MaxTransactSize', 4]
, ['MaxReadSize', 4]
, ['MaxWriteSize', 4]
, ['SystemTime', 8]
, ['ServerStartTime', 8]
, ['SecurityBufferOffset', 2]
, ['SecurityBufferLength', 2]
, ['Reserved2', 4]
, ['Buffer', 'SecurityBufferLength']
]
}
module.exports = {
request:[
['StructureSize', 2, 33]
, ['FileInformationClass', 1, 0x25] // FileBothDirectoryInformation plus volume file ID about a file or directory.
, ['Flags', 1, 0]
, ['FileIndex', 4, 0]
, ['FileId', 16]
, ['FileNameOffset', 2, 96]
, ['FileNameLength', 2]
, ['OutputBufferLength', 4, 0x00010000]
, ['Buffer', 'FileNameLength']
]
, response:[
['StructureSize', 2]
, ['OutputBufferOffset', 2]
, ['OutputBufferLength', 4]
, ['Buffer', 'OutputBufferLength']
]
}
module.exports = {
request:[
['StructureSize', 2, 49]
, ['Padding', 1, 0x50]
, ['Flags', 1, 0]
, ['Length', 4]
, ['Offset', 8]
, ['FileId', 16]
, ['MinimumCount', 4, 0]
, ['Channel', 4, 0]
, ['RemainingBytes', 4, 0]
, ['ReadChannelInfoOffset', 2, 0]
, ['ReadChannelInfoLength', 2, 0]
, ['Buffer', 1, 0]
]
, response:[
['StructureSize', 2]
, ['DataOffset', 1]
, ['Reserved', 1]
, ['DataLength', 4]
, ['DataRemaining', 4]
, ['Reserved2', 4]
, ['Buffer', 'DataLength']
]
}
module.exports = {
request:[
['StructureSize', 2, 25]
, ['Flags', 1, 0]
, ['SecurityMode', 1, 1]
, ['Capabilities', 4, 1]
, ['Channel', 4, 0]
, ['SecurityBufferOffset', 2, 88]
, ['SecurityBufferLength', 2]
, ['PreviousSessionId', 8, 0]
, ['Buffer','SecurityBufferLength']
]
, response:[
['StructureSize', 2]
, ['SessionFlags', 2]
, ['SecurityBufferOffset', 2]
, ['SecurityBufferLength', 2]
, ['Buffer', 'SecurityBufferLength']
]
}
module.exports = {
request:[
['StructureSize', 2, 33]
, ['InfoType', 1, 1]
, ['FileInfoClass', 1]
, ['BufferLength', 4]
, ['BufferOffset', 2, 0x0060]
, ['Reserved', 2, 0]
, ['AdditionalInformation', 4, 0]
, ['FileId', 16]
, ['Buffer','BufferLength']
]
, response:[
['StructureSize', 2]
]
}
module.exports = {
request:[
['StructureSize', 2, 9]
, ['Reserved', 2, 0]
, ['PathOffset', 2, 72]
, ['PathLength', 2]
, ['Buffer', 'PathLength']
]
, response:[
['StructureSize', 2]
, ['ShareType', 1]
, ['Reserved', 1]
, ['ShareFlags', 4]
, ['Capabilities', 4]
, ['MaximalAccess', 4]
]
}
module.exports = {
request:[
['StructureSize', 2, 49]
, ['DataOffset', 2, 0x70]
, ['Length', 4, 0]
, ['Offset', 8]
, ['FileId', 16]
, ['Channel', 4, 0]
, ['RemainingBytes', 4, 0]
, ['WriteChannelInfoOffset', 2, 0]
, ['WriteChannelInfoLength', 2, 0]
, ['Flags', 4, 0]
, ['Buffer', 'Length']
]
, response:[
['StructureSize', 2]
, ['Reserved', 2]
, ['Count', 4]
, ['Remaining', 4]
, ['WriteChannelInfoOffset', 2]
, ['WriteChannelInfoLength', 2]
]
}
var BigInt = module.exports = function(n, v){
if(BigInt.isBigInt(n)){
this.buffer = new Buffer(n.buffer.length);
n.buffer.copy(this.buffer, 0);
this.sign = n.sign;
} else {
this.buffer = new Buffer(n);
this.buffer.fill(0);
this.sign = 1;
v = v || 0;
if(v != 0){
if(v<0) {
this.sign = -1;
v = -v;
}
v = v.toString(16);
var size = Math.ceil(v.length/2)
, carry = size*2 - v.length
;
for(var i=0; i<size; i++) {
var start = (size - i - 1) * 2 - carry;
this.buffer.writeUInt8(
parseInt( start == -1 ? v.substr(0,1) : v.substr(start, 2), 16)
, i
);
}
}
}
}
/*
* STATICS
*/
BigInt.isBigInt = function(v){
return v && v.buffer && Buffer.isBuffer(v.buffer);
}
BigInt.toBigInt = function(n, v){
return new BigInt(n, v);
}
BigInt.fromBuffer = function(b, sign){
sign = typeof sign == 'undefined' ? 1 : sign;
var bi = new BigInt(0);
bi.sign = sign;
bi.buffer = b;
return bi;
}
/*
* ADD / SUB
*/
BigInt.prototype.add = function(v){
if(!BigInt.isBigInt(v)) {
v = BigInt.toBigInt(this.buffer.length, v);
}
if(this.sign != v.sign){
return this.neg().sub(v);
}
var carry = 0
, n = Math.max(v.buffer.length, this.buffer.length)
, result = new BigInt(n);
;
for(var i=0;i<n;i++){
var r = ( i<this.buffer.length ? this.buffer.readUInt8(i) : 0 )
+ ( i<v.buffer.length ? v.buffer.readUInt8(i) : 0 )
+ carry
;
result.buffer.writeUInt8(r & 0xFF, i);
carry = r >> 8;
}
result.sign = this.sign;
return result;
}
BigInt.prototype.neg = function(v){
var result = new BigInt(this);
result.sign *= -1;
return result;
}
BigInt.prototype.abs = function(v){
var result = new BigInt(this);
result.sign = 1;
return result;
}
BigInt.prototype.sub = function(v){
if(!BigInt.isBigInt(v)) {
v = BigInt.toBigInt(this.buffer.length, v);
}
if(this.sign != v.sign) {
return this.add(v.neg());
}
var carry = 0
, a = new BigInt(this)
, b = new BigInt(v)
, n = Math.max(a.buffer.length, b.buffer.length)
, result = new BigInt(n)
, sign = this.sign
;
if(a.abs().lt(b.abs())){
var t = a;
a = b;
b = t;
sign *= -1;
}
for(var i=0; i<n; i++){
var va = ( i<a.buffer.length ? a.buffer.readUInt8(i) : 0 )
, vb = ( i<b.buffer.length ? b.buffer.readUInt8(i) : 0 )
, c = 0
, r = va-vb-carry
;
while(r<0){
r+=0xFF;
c--;
}
result.buffer.writeUInt8(r & 0xFF, i);
carry = (r >> 8) + c;
}
result.sign = sign;
return result;
}
/*
* EXPORTS
*/
BigInt.prototype.toBuffer = function(){ return this.buffer }
BigInt.prototype.toNumber = function(){
var b = new Buffer(this.buffer.length);
for(var i=0; i<this.buffer.length; i++){
b.writeUInt8(this.buffer.readUInt8(this.buffer.length - i - 1), i);
}
return parseInt(b.toString('hex'), 16);
}
/*
* COMPARE
*/
BigInt.prototype.compare = function(v){
if(!BigInt.isBigInt(v)) {
v = BigInt.toBigInt(v, this.buffer.length);
}
var n = Math.max(v.buffer.length, this.buffer.length);
if(this.sign > v.sign) return 1;
if(this.sign < v.sign) return -1;
for(var i=n-1;i>=0;i--){
var a = ( i<this.buffer.length ? this.buffer.readUInt8(i) : 0 )
, b = ( i<v.buffer.length ? v.buffer.readUInt8(i) : 0 )
;
if(a!=b){
return a > b ? this.sign : -this.sign;
}
}
return 0;
}
BigInt.prototype.lt = function(v){
return this.compare(v) < 0;
}
BigInt.prototype.le = function(v){
return this.compare(v) <= 0;
}
BigInt.prototype.gt = function(v){
return this.compare(v) > 0;
}
BigInt.prototype.ge = function(v){
return this.compare(v) >= 0;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name":"SMB2"
, "description":"SMB2 Client"
, "homepage": "https://github.com/bchelli/node-smb2"
, "version":"0.1.0"
, "engines": [
"node"
]
, "author":{
"name": "Benjamin Chelli"
, "email": "benjamin@chelli.net"
, "url": "https://github.com/bchelli"
}
, "main":"lib/smb2.js"
, "repository": {
"type": "git"
, "url": "https://github.com/bchelli/node-smb2"
}
, "dependencies": {
"ntlm": "~0.1.1"
}
, "keywords": [
"SMB"
, "SMB2"
, "SMB3"
, "NTLM"
, "CIFS"
, "Samba"
],
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment