Javascript - Simple - getting an Ip from a URL - javascript

I am simply trying to achieve something like this:
function getIp() {
var urlenter = document.getElementById('io');
var IPOUT = urlenter.IpAdress !------HERE!!!!!!!!------!
location.href = IPOUT;
}
so if I typed 'facebook.com' in 'io' it would set the href to the ip adress of facebook.com

JavaScript doesn't have any concept of hostnames or IP addresses. You would have to use an external service to resolve an IP address from a hostname.

That's not possible with JavaScript alone.
The resolving between IP addresses and hostnames are handled at the DNS level, which is way before JavaScript ever comes to life. It only gets to know the host it is connected to, whether that is by an actual hostname or an IP address.
Still though, you could have JavaScript connect to an outside service, e.g. your server via Ajax, and have it make the resolving.

Related

Get matching LAN players

I'm running a simple node.js server that also gots a webinterface using express.
Every time a clients goes on the website I'd like to find out who else from this clients network is connected.
I know that I can read out the localIP address of every client using some syntax like this.
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
... but how can I determine which clients are in the same network? (LAN)
I'm aware that the IP-address is nearly unnecessary/needless because of the currently unkwown Network ID - but how can I determine the networkID on the nodeJS server?
Edit: Is this also possible using socket-io with node.js?
Any help would be really appreciated. Thanks.
If you just want to check if two players are in the same LAN, looking at their remoteAddress using your code should be enough. You might want to assign unique IDs to each player, so if you have 2 players with different IDs but same IP address, it means that they are in the same LAN.
On the other hand, if you really want to obtain their local IP address for other purposes, you might want to look at this answer on how to process os.networkInterfaces()

Securing REST API calls with client-side token

I have a node.js REST API and I want to restrict POST/PUT/DELETE calls to a predefined list of "sources" (web applications which I do not own the code).
The only way I see to achieve this is to put a token on the client-side (something like Google Analytics in JS files) but I have no idea how to secure this since the token will be accessible in the static files.
What strategy should I use ? JWT and OAuth2 seem not indicated since it requires first user authentication, but what I want to authenticate is not user but webapps.
Your question is slightly unclear. You could mean either (a) that you want to strongly encourage the user to use the app and prevent other code from maliciously making your user perform an action, or (b) that you want to absolutely prevent your user from using other code to access your server.
The first option is possible, and indeed a very good idea. The second is impossible, based on the way the Internet works.
First, the impossibility. Essentially, client-side code is there to make life easier for your client. The real work will always be done on the server side -- even if this only means validating data and storing it in the database. Your client will always be able to see all the HTTP requests that they send: that's the way HTTP works. You can't hide the information from them. Even if you generate tokens dynamically (see below), you can't prevent them from using them elsewhere. They can always build a custom HTTP request, which means ultimately that they can, if they really, really want, abandon your app altogether. Think of your client-side code as merely making it easier for them to perform HTTP requests and abandon any idea of preventing them "doing it wrong"!
The much better option is CSRF protection, which gives the best possible protection to both your server and the client. This means sending a generated token to your client when they first log on and verifying it (either by looking it up or decrypting it) when they send it on every request. This is the basis of JWT, which is a beautiful implementation of a fairly old system of verification.
In the end your API is public, since any random website visitor will have to be able to interact with the API. Even if you use tokens to restrict access somewhat, those tokens by definition will have to be public as well. Even regularly expiring and renewing the tokens (e.g. through a backend API, or by including a nonce algorithm) won't help, since those new tokens will again be publicly visible on the 3rd party's website where anyone can fetch one.
CSRF protection can help a little to avoid cross-site abuse within browsers, but is ultimately pointless for the purpose of preventing someone to write an API scraper or such.
The best you can do is use the tokens to identify individual site owners you granted access to, vigilantly monitor your API use, invalidate tokens when you think you're seeing them abused and contact the site owners about securing their tokens better somehow (which they'll have the same problem doing, but at least you have someone to blame cough cough).
You can use hmac to secure this :
Each client has a unique couple of key public/private (for example "public" and "private").
When client send request, he has to send a nonce + his user public key + the hmac of nonce+public key with his private key.
When server handle request, the server retrieve the client according to his public key, get the secret key of the user, then verify the signature.
Client, sample call on /api
var nonce = "randomstring";
var pk = "aaa";
var sk = "bbb";
var string = "pk="+pk+"&nonce="+nonce;
var crypto = require('crypto');
var hmac = crypto.createHmac('sha512', sk).update(string).digest('hex');
// send this payload in your request in get, put, post, ....
var payload = string+"&hmac="+hmac;
request.post({uri:"website.com/api?"+payload}, ....
And
Server side, security check
var nonce = req.query.nonce;
var pk = req.query.pk;
var hmac = req.query.hmac;
// retrieve user and his sk according to pk
var sk = getUser(pk).sk
// rebuild payload string
var string = "pk="+pk+"&nonce="+nonce;
var crypto = require('crypto');
var hmac_check = crypto.createHmac('sha512', sk).update(string).digest('hex');
if(hmac_check === hmac) { // request valid }else{ // invalid request }

LDAP Bind Error using node.js and ldapjs

I am trying to implement a basic ldap bind with the following node.js file. Unfortunately, I keep getting a bind error with code 128. I looked online and found no references of code 128. The LDAP server I am trying to search is an eDirectory. Does anyone have any experience with this or have you had similar problems? My node version is v0.10.22 and my ldapjs version is v0.7.1
var ldap = require('ldapjs');
var creds = {
url: "ldaps://ldap.url.com:636",
bindDN: "cn=ldap,o=com"
};
var opts = {
filter: "(cn=username)",
scope: "sub"
};
function authDN(client, dn, password, cb) {
client.bind(dn, password, function (err) {
client.unbind();
cb(err === null, err);
});
}
function output(res, err) {
if (res) {
console.log('success');
} else {
console.log(['Error',err.code, err.dn, err.message ]);
}
}
var client = ldap.createClient(creds);
authDN(client, '(cn=username)', 'password', output);
This authenticates when i added the following to the top of my file:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
I haven't researched enough to know why this works but I found this answer here: https://github.com/mikeal/request/issues/418
In general when debugging an eDirectory issue, ask for access to iMonitor, so you can look at DStrace with the +LDAP option. That would show you what the LDAP server is sending back, making troubleshooting easier.
To augment Kaiser's answer, an explanation on why adding process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; to the code may work is found at the top of this link: https://github.com/visionmedia/superagent/issues/205.
Potential fixes:
Add process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; to the top of your script for node v0.10.x (and above)
Setup a trusted CA certificate on the server instead of a self-signed certificate (must have server admin rights and pay for a valid cert)
Use the LDAP server IP or load balancer IP instead of dns for the url parameter.
Because you are using the secure protocol (ldaps:// instead of ldap://), and I'm assuming you are trying to connect to a server with a self-signed certificate, you will get a failure if using node v0.10.x (and probably all later versions as well) and the code/module you are using doesn't specifically set the process.env.NODE_TLS_REJECT_UNAUTHORIZED to false.
NODE_TLS_REJECT_UNAUTHORIZED was changed to true by default for a reason. If you choose to set NODE_TLS_REJECT_UNAUTHORIZED to false, you are opening up more security risks, and I would advise only doing this on private networks at best, and never in production environments. Without going down a security discussion rabbit hole, it's always best to use a cert signed by a CA. More info on the differences on certs can be found here. This can also cause problems if your application is robust enough to make multiple connections to various secured servers where only some use self signed certs, again mentioned in this link.
If the cert wasn't self-signed, you most likely shouldn't be getting this error, so another potential fix is to setup and use a trusted CA Certificate on the LDAP server instead.
On the other hand, if you are using a normal, non-secure ldap connection (not through TLS), and/or you get this error only occasionally while other times it goes through, you should try setting the ldap url to the LDAP server IP or load balancer IP (and use port 3268 to allow searching in all domains). In larger network setups this will avoid potential round robin dns queries that sometimes point you to a slow server or one you can't route to.

Get running python server IP address in Javascript

I have a python flask app running on my server:
if __name__ == '__main__':
port = int(os.environ.get("PORT", 6600))
app.run(host='0.0.0.0', port=port)
And I have a JS script getting information from that app, I don't want to change manually th IP or domain in the JS script every time I deploy or change the domain so I'm asking is there any way for the JS to know the IP or hostname of the python app ?
Here's my structure:
index.py <= main app
static
**index.html
**script.js
Thanks
Register a domain name and stick with it. Use the domain name in your javascript and/or config.
Make sure that the registrar provides an interface for updating the "A record" (IP address) and point it at your server. Whenever you change IP address, update the A record for your domain.
If I understand your question correctly, you pretty much have two options at your disposal depending on your setup.
Option 1: If your JavaScript code is running on the same machine as your Python script, you could simply always just access it from 127.0.0.1 from your JavaScript code (because binding to 0.0.0.0 will make the Python server accessible from all interfaces, including the loopback interface at 127.0.0.1).
Option 2: If your JavaScript code lives on a remote server, your simplest solution is going to be to use some kind of Dynamic DNS service as an intermediary. So you'll end up with two domains for your Python server: one static one available to the rest of the world, like www.mypythonserver.com, and one dynamic DNS entry only known by your JavaScript code, like mypythonserver.noip.me (hard-coded permanently into your JavaScript code). Both of these domains should always resolve to your Python server's host address, with no manual intervention necessary for the dynamic DNS entry.
You can use the templating in the script file which would get filled with the port number when user requests the script.
There are many templates available at :
https://wiki.python.org/moin/Templating
Usually it would be like
// in script.js
var myport = {{ port }};
and in your python code :
# if request is for script.js
# respond with template
request.send(my_templating_engine('script.js' , port))

How can a server find real client IP address?

I can only access the internet from my place from behind a NAT and a proxy. This site however also shows my machine's private LAN address, as well as my NAT's public address. They are apparently using javascript in the process, but I can only find code where they set the value, but not how they find it. So, how can we find out the private IP address of a client machine using javascript?
They're using Java for that:
<span class="pbb" id="lanip"><b>Router IP Address Testing...</b></span>
<script>
function MyAddress(IP)
{ document.getElementById("lanip").innerHTML = IP; }
</script>
<applet code="MyAddress.class" MAYSCRIPT width=0 height=0>
You Need To Enable Java For This To Work
</applet>
Are you sure you're behind just a NAT router? If you're behind a proxy, the proxy might well be adding an X-Forwarded-For header.

Categories

Resources