Current standard of authentification What is the current standard of authentification?

I thought it is server and client authentification.

But I typed for e.g. https://www.google.com/ and checked the packages in wireshark. And there is only a server authentification. I am wondering why the server is never sending me the TLS CertificateRequest-message (Isn't it the only way how client-authentification can be accomplished?).

Shouldn't that be standard and why why should a HTTPS-Webserver trust me?
(Retrieving a certificate from a common CA should be easy for my webbrowser)

Who said the server has to trust you? For many HTTPS sites, a server does the same thing for everyone; Google is happy to do a search for anyone, and nothing it sends you is necessarily even a little bit sensitive from their point of view. If Google doesn't care who you are, there is literally no reason to do client authentication.

If client authentication is desired, you still don't need to do so through TLS. Once you have a secure channel to another party, you can send info along that channel, so once the server has authenticated the client can just authenticate by sending a password. That doesn't work for the server because there are typically many clients, all of whom would need to know the password, and so could impersonate the server to another client. In contrast, it's not as big a problem if the server can impersonate a client, because servers tend to be more trusted than clients (they'll take anyone as a client, the reverse is not true). If the client sends a password, the server must have already authenticated, so that's why that must happen in TLS, while client auth doesn't have to happen then.

Lastly, since passwords do work OK for client auth and are easier for users to deal with, most sites use them. TLS client certs from CAs have little point in most cases anyways; if pseudonymity is fine you can just have people directly upload a client cert of their choice, if it isn't you normally have a more authoritative issuer than just any commercial CA (i.e. have one trusted issuer, which is often just yourself)


How hard is it to distinguish between remote access to a virtual machine vs a piece of hardware? Let's say I have full access to a remote machine (specifically, root on a Linux). What is the best method to check whether this is a real piece of hardware or a virtual machine?

Most of the methods that I have seen rely on looking at various hardware-related identifiers using tools such as lshw. It seems to me that these methods are prone to some sort of man-in-the-middle attacks.

Thanks in advance for references or any other information.

It depends. If it attempts to hide that it's an VM, it can be hard. This can be the case with for instance VM's used for analyzing malware.

This paper from Symantec goes into some detail. In short, it's usually possible to detect, even if the VM, is trying to hide it, by running instructions to put the CPU in a specific state, and then run some instruction that forces the hypervizor to execute, and check the state of the CPU afterwards.

Timing attacks can also detect a hypervizor, but may be difficult if you have no baseline.

A stock VM from for instance Azure will not attempt to hide that it's an VM, and it will be obvious that it is a VM, from descriptors as you say.


Phone Number Appears to Have Been Temporarily Hijacked What Happened:

At 8:40am Telegram sends me a login code via the Telegram desktop app.
At 8:44am Telegram informs me that someone has logged into my
account via ip address #1 (appears to be PIA vpn)
I immediately go and revoke access and begin the process of setting
up 2fa with a password.
At 8:45am Telegram sends me a login code via the Telegram desktop app.
At 8:46am Telegram sends me a login code via the Telegram desktop app. Somewhere around this time I disable wifi on my phone and notice that my phone is not connecting to the mobile
internet.
At 8:48am Telegram informs me that someone has logged into
my account via ip address #1
At 8:48am Telegram informs me that someone has logged into my account via ip address #2
I revoke access to both.
I finish setting up 2fa.
I restart my phone, my mobile internet is back and I get 2 smses informing me that my MMS and WAP Service Settings have arrived.  These settings appear legitimate.

Other Important Info:

My phone company says no one has contacted them / no settings were altered on their end.  They haven't been much help otherwise.
My sms log on the phone company's website show two smses received from Telegram that I never saw and never arrived at my phone.  I know this is Telegram's number because I went through the process of logging into Telegram's web interface.
No strange apps have sms access permissions on the phone.
Anti-virus apps show nothing.
Galaxy S8+, up to date, not rooted
No other attacks, no other accounts appears to have been compromised.

Questions:

Have any attacks like this been reported before? (can't find any)
What else can I do to try to figure out what happened?

I realize that it's also likely that my phone is owned or that there is a telegram exploit.  Any other information would be helpful.

1. Have any attacks like this been reported before? (can't find any)

Sim card 'hijacking' is possible, a PAC code can be used when transferring a current number to a different existing network. However, when transferring the current number to another sim card (same network), this can be a speedy process. Linus Tech Tips experienced this type of hijacking.

Although, this would involve the old sim card being deactivated, for security purposes. So this sounds less viable given what you described.

2. What else can I do to try to figure out what happened?

Samsung Galaxy S8's were shipped with Android 8.0 and above. So sandboxing was introduced by then. Review all installed apps that have SMS permissions, or any permissions that could elevate, control and make phone calls and/or read SMS.

Less likely, but your version of Android could contain an exploit, review CVEs for your Android version. Which may have provided an attack vector to access your SMS messages. With rooting an Android device, we only know because the modified kernel does not have signed code. However, if a vulnerability was identified which allowed a jailbreak, privilege escalation could occur without the user's knowledge. Although, this is merely speculation, and it's particularly unlikely you are running some type of spyware.


buffer/heap overflow - register of what is executed When buffer overflow/heap overflow is executed, is EIP the one that tells which part will be executed next? Also, when exploiting the part that has buffer overflow vulnerability, after execution, will ESP point to the start of the exploit codes (which will be some combinations of shell codes and gibbersih)?

If this seems too vague, can anyone show me what each register will point to during the execution of exploits?

will ESP point to the start of the exploit codes (which will be some combinations of shell codes and gibbersih)?

Actually, its the EIP that will point to the start of the exploit code instead of ESP. In a classic stack buffer overflow, ESP will continue to be where it would have been with/without exploit code. The only thing that you overwrite is the EIP changing it to a different address in memory - where you've already 'planted' your exploit code somehow.

To illustrate lets see the diagram of a stack and note values of various registers:

Lets assume there is a exploitable buffer in the callee function where an arbitrary amount of data can be provided (gets, rougue srtcpy etc.).
The attacker calculates the exact number of bytes before the place on stack where the return address (EIP) is stored. So the input could be of form (each block corresponding to each red line below).

AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA 0834FD4C

where 0834FD4C is the new instruction pointer attacker wants to plant at the saved EIP location and preceding A's are just pads to reach to the EIP (remember stack grows down).

After the overflow, lets say the stack looks like this:

At this point, attacker has successfully planted the new EIP. Whenever the callee function returns, the ret instruction will pop the saved EIP (now 0x0834FD4C) to %eip register and the control flow will resume from this memory address and will start executing whatever instructions it finds there. Again, the attacker has to make sure that he has planted the exploit code at this location beforehand.

Post callee return:
EBP : Can change or cannot change based on what attacker provides in the data of overflown buffer. Remember that since he has to tromp EBP before he reaches EIP, certainly he'll have to provide a value for EBP as well. Generally the attacker will be diligent enough to enumerate the stack to determine the current EBP and plant it into the payload so that it remains the same as before. For eg. he could(and should) provide something like:

AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA 082376ED 0834FD4C

Where 082376ED is the existing EBP. This will make sure that it is not changed to an arbitrary value in the mission to overwrite the EIP.

EIP : It is changed to the new value

ESP : It will revert back to the same value irrespective of buffer overrun or not.

So after the function returns, you'll live in the stack frame of the old caller but will be executing some other code.

Smashing the Stack for Fun and Profit  is an excellent source for any further information.


Diceware & Database hosting I'm currently setting up a new SQL database with DotEasy as my Hosting/Database provider.

I've heard a lot about Diceware being one of the best methods of creating a really strong password, so I figured I'd use it to create a password for my database.

DotEasy's form says that password strength must be over 55/100. So I created my password (which is 6 words long) and then went to enter it into DotEasy, the strength bar jumped to 22/100, then 30/100 as I continued to type my password, but then fell down to 0/100 when I finished typing it in. I don't understand this, I then tried a much simpler password ("holly1996") and the strength meter jumped to 68/100...

Does this mean that my diceware password would be easier to crack than I've heard, or does it mean that DotEasy have a bad password-strength rating system in place?

It means that DotEasy has a bad password strength rating system.  If I recall correctly they are a pretty cut rate hosting platform.  If you are looking for something dirt cheap they are probably the way to go.  If you are looking for quality, you might look into a more expensive/respected hosting provider.

Best of luck!


Trying to examine URL redirection in Wireshark I clicked on a link (indistannews.com) and was redirected to a different website (sexiniowa.com). [Warning - the latter site is a pornography website].

I looked at the transaction in Wireshark to try and see how I was redirected. All I see is a 3-way TCP handshake initiated by my client to the original correct IP (50.63.202.1), and then immediately after a NEW TCP handshake to a totally different IP (63.163.163.134) which contains the pornography.

Why did my client choose to drop the original connection and initiate a new connection to this second IP? What information in the first 3-way handshake (if any) prompted my client to do this?

-Nick

A TCP handshake does not contain any redirect information. If you check instead at the application layer you see:

$ curl -v http://indistannews.com/
...
< HTTP/1.1 301 Moved Permanently
...
< Location: http://sexiniowa.info

Since this is a 301 permanent redirect the client does not even need to visit the original site again but will instead use the new location on repeated tries. Only on the first try it will visit the original site to receive the redirect. And this is what your packet capture might show.


Is it possible to defend against user enumeration during registration? I am currently reading the book "Web Security of Developers" and it talks about avoiding Username Enumeration, and it makes no mention of the registration/signup page for your system. I've searched the web and haven't found anything either.
It seems to me that an attacker could simply try signing up for your website with a series of usernames, and that would constitute username enumeration to the same extent as overly informative login failure or password reset pages.
Is this assessment correct or is there something I've overlooked here? Also, if I am right about this, is there a known mitigation approach?

Maybe we could consider that using usernames instead of email for authentication allows this misbehavior.
If only the email address are allowed to login, then it is not a problem to reveal that an username is already used (because it is not sufficient to log in). And because email addresses are unique, there are few chances that someone tries to register with an already existing email address.
If it's happen, it is possible to not display any warning and to send an email saying "you tried to register again with this email address, if you forget your password, use the dedicated function. If it was not you, don't worry your account was not modified".
Furthermore, by using an email confirmation (with activation link) after registration, a legitimate user who misspelled his email address will be able to figure it out because he will not receive the email confirmation. So even if he used an existing email address by mistake, there is no user enumeration and he can know that the registration was not complete.


What practical damage a compromised/malicious third-party JavaScript can cause? It is well-known that third-party JavaScript inclusion is risky, I wonder what actual damage can be caused if the third-party script is malicious. Of course the script can cause as much damage as possible to its own DOM, other than that, can it affect other DOMs, can it cause any damage to the browser or the host computer?

Perhaps the most prolific recent attack involving compromised scripts hosted by third-party servers is Magecart, which targeted scripts for Magento.  This attack compromised thousands of sites, including British Airways and Ticketmaster, and others.  It was used to steal credit card information of hundreds of thousands of users of these sites.  See https://www.csoonline.com/article/3400381/what-is-magecart-how-this-hacker-group-steals-payment-card-data.html for more info.

The attackers launched the attack by modifying javascript scripts hosted on third-party sites (such as Github and various CDN's) that the victim sites incorporated into their own sites.

Preventing this attack is rather simple.  This is exactly the type of attack that Subresource Integrity is designed to defend against.


Android antivirus apps Is it necessary to have an internet connection to run and properly scan an android device for viruses or malware using an anti-virus app? How an anti-virus app scan an android device for infected files and viruses?

You need an internet connection to download it and for it to update its threats database. Apart from that, you don't really need internet access to have it scan your device. As for how it works, each anti-virus has a threat database which uses to scan files for malicious signatures. Some more advanced will also look for abnormal behavior in the execution of an app, like network connections, root attempts etc.


How are shopkeepers getting the MAC address of wifi enabled smartphones? It is clear that some big malls are tracking all the wifi-enabled mobile phones before they are connected to the network... How can this be done?

I have a similar issue... how to get the MAC address of a mobile phone when it comes near my network but is not connected to it.

Most WiFi enabled devices broadcast their Mac address when probing for networks to join in the vicinity.

By placing your own WiFi device in promiscuous/listening mode and utilizing a tool like Aircrack-ng, you can see and record all broadcast traffic enabling you to see if a device with a specific MAC address comes within earshot of your listening device.

See: Is your smartphone broadcasting your movements when you shop?


How to inject a key (physically) on a huge number of devices? The system I am designing has a huge number (assume millions) of individual devices, and each device needs to be injected with a unique symmetric key dedicated to that device. Each device also has a serial number with which it can be physically tracked and accounted for.

Question: what industry-standard approaches exist for injecting keys into such a huge quantity of devices?

I am interested in the physical mechanisms that are available on such an industrial scale. The solution can be a combination of hardware and software.

Associated Requirements:

No two devices can get the same key. The system needs to ensure that each key is only used once.
For reasons of traceability during the lifecycle of the device, the system needs to know which serial number received which key.

Since you seem unable (likely understandably so) to give any more information, I am going to rephrase your situation so you can determine if we are on the same level. And make an assumption that looks like reasonable.

For all intent and purposes the symmetric keys are not keys but just data, since we get them "prefabricated" out of some system. Thus, in other words, you are asking how can I send some "private data" (= keys) to a group of "users" (= devices) over an "insecure channel" (= the factory and it's employees), with the users having an uniquely identifying feature (= serial number) which is easily known and/or imitated by a malicious user.
I will also amuse losing some devices (or having a cost of reprogramming) due to an attack is not a problem.

What you need is for each user to be able to request its data only ONCE.

The user connects to your server using a secure authenticated channel (I would suggest some kind of SSL connection).
The user sends its ID (serial number) to the server.
The server checks if the data (symmetric key) corresponding to this ID has not been handed out (is not flagged).
Is not flagged: The server sends the user its data (symmetric key) and flags this key as handed out in it's DB-system.
Is flagged: The server does not deliver the data to the user.

The device should only be able to work if it has received a symmetric key from this server. This could be a final part of the production process, let the device initialize (get the key) and check that it has received a key (without the device letting know that the key is of course).

Should someone breach your factory and start sending malicious requests to the server, it cannot breach the security (though it will involve some costs due to some devices being manufactured with already used serial numbers, either the cost of a device must be very small or you can reprogram the serial number, which should also reset the symmetric key of course).

The whole point of this system is to reduce the size of the secure environment, only the server and its DB need to be secure and those can be located off-site if needed. Assuming the server and DB are safe and the device cannot be read or abused between initialization and being in the customers possession, once a device leaves the factory, the fact it turns on will let the customer know it has its key and only the server (and DB) know this key.

I believe the device cannot be read or abused between initialization and being in the customers possession falls outside the context of this SE as it is about physical security. One note I do like to make is that if the device could be initialized in front of the customer, say by a vendor under customer supervision this could greatly decrease the potential for this condition to impact security.

Edit: response to remarks made by Gilles

  the server has no way to know whether the serial number sent in the request is genuine

I read the comment from the OP saying that "You can assume for this question that keys have already been generated and have an associated identifier" as "there is a DB containing {serial-number, key} pairs". Thus the server can check (does) if the serial number is genuine.

  it means that some devices will be bricked as communication breaks down for one reason or another

I'm not sure how to interpret this but I read this as "if communication breaks down during initialization then the device becomes bricked".
I presumed this would be a network internal to the factory or at least the same company making communication problems rather unlikely (though possible, true). Only when the communication fails during sending of the key to the device is there a problem by the way.
When I said "This could be a final part of the production process" I did not mean this should happen outside the companies network,
just that it's the most secure to have it as close to the end as possible, sorry for any miscommunication.

  it enables a trivial DoS attack where an attacker claims all serial numbers

It does allow a DoS attack against the serial numbers. This is because I made the assumption that security was a very important concern for this device and that resetting a device would be an acceptable trade-off to security.
However as you will need to be breaching the companies internal network first I do not see this to be that big of a risk. However the attacker will still need to guess correct serial numbers and given a decent lengthy serial the hit-rate should be rather low as we know the production capacity and thus can limit the query limits of the server as an extra security measure.

  It also allows quite a wide range of impersonation scenarios that the “only once” rule does not prevent, for example: a company orders 100 devices, provisions 90 and keeps the last 10 as backups; an attacker impersonates one of those 10 and gets a key that the company has recorded as belonging to one of its legitimate devices. You need to provision a key (not necessarily the one that will be used by the final customer, it can be a temporary provisioning key) before the device leaves the manufacturer's secure supply chain.

I should have made it clear that the "initializing" should take place in the companies secure network. Either as part of the production process or as part of the sales (I assumed part of the company but did not make this clear in my "note") but I did say in my "note" that the vendor did have to initialize the device (under supervision of the customer). So any scenario where a customer has a not initialized device should not occur.

  I don't think this question is answerable, given that it is extremely general and does not say anything about the device manufacturing process, the distribution process, or the device capabilities.

I do agree that given the general nature of this question an optimal (or very good) solution can not be given. The solution I provide has an inherent cost in the possibility of needing to reprogram serial numbers (or bricked devices depending on implementation). But this is intended to allow a general answer without impacting security. I believe a better solution would involve PKI for client authentication but this is prohibited by the OP.


Is it possible to brute-force a CVV code? If I'm not wrong, the CVV code almost always follows a certain pattern based on the credit card number and dates. What are the possibilities to go through to hypothetically brute-force a CVV code? Is an online attack possible?

Actually it was possible, at least for Visa cards. There was no per-card lockout across the entire network, so by hitting different payment processors (to prevent from reaching any brute force limit they might have) you could brute force a CVV2. I am not sure whether this is still possible, I would expect (and hope) that Visa implemented network-wide protections against this.


JWT for email validation of an account I am thinking of using the this registration flow for my site:

1) User registers by entering email and password.

2) Enter the email and hashed password into my database

3) I then construct an email with my url + jwt (contains e-mail and expires in 1 hour) string as a parameter.

4) User receives email and clicks on link.

5) Link sent to my server where I parse the parameter and check if the jwt is expired.

6) If not expired I then take the email and mark the account as validated in my database.

Are there any obvious holes in this approach which would leave to big vulnerabilities?

For a typical email activation it should be okay, however for a password reset or an email confirmation which logs you in afterwards you usually want to ensure tokens are single use.

That ensures that a man-in-the-middle logging requests (ie. a corporate network administrator) can't follow the same link and log in after the legitimate user. Your expiry limits the window where this is a possibility though.

You also need to be careful with any other user input that you sign for other purposes. You want to ensure that a user couldn't exploit some other functionality by entering input that will generate a valid token for your email activation. You might like to include some random "action" string in your payload to ensure tokens generated for other purposed can't be used for email activation.


Smartphone app as a U2F hardware token via Bluetooth? Quoting from agl's article from Mar 2018:

  At the time of writing, all Security Keys are based version one of FIDO’s “Client To Authenticator Protocol” (CTAP1). [...T]he core protocol [can be] transported over USB, NFC, and Bluetooth.

Are there any roadblocks for writing an app for my Android/iOS phone, which would make it work as a U2F hardware token over Bluetooth (assuming my PC has Bluetooth connectivity)? Are there reasons why this would be a bad idea? I tried to search for such an app, but didn't manage to find anything.

Definitely Less Secure

The two biggest concerns apply to all software tokens, not just FIDO.

Platform Vulnerabilities

Hardware security keys provide a relatively strong protection of their cryptographic secrets (either a private key or a seed value). This protection is severely reduced when you implement the functionality on a general purpose OS. If the OS is compromised, an attacker could steal the secret. This extends the risk to include firmware bugs, debug modes, OS vulnerabilities, other software, user issue, etc.

With the well-known problems keeping Android phones up to date, it is especially risky on that platform.

Exclusive Control

The second issue is that compromised credentials are apparent with a hardware token. A user probably will never notice when their smartphone is hacked. In all likelihood, the 2FA app will continue to function normally. With a hardware token, a user will definitely notice when their token is lost or stolen.

You can generally assume a user has exclusive control over their 2FA hardware until shortly before it is reported lost. There can be no such assumption for 2FA credentials stored in software.

Bad Security, But Possibly Worth The Trade-off

In the end, a software 2FA implementation is more prone to being compromised and less prone to detecting successful attacks.

However, it will be cheaper and easier to provision if your users already have supported devices.

This is a classic cost-vs-security trade-off, and organizations make decisions like this all the time. Personally, given the low cost of hardware tokens, I would never choose the app, even if it were free.


Can display a GIF in  tag causing Client-side DOS SVG image can be used in DOS user browser with billion laugh attack. Can we do the same with other image types? especially GIF?
Thanks everyone.

Possibly, though not so dramatically. The real trick of billion laughs attacks is that they're exponential: increasing the number of layers of recursion increases the total size (for the classic example) by a factor of 10. That's much more impressive than usual expansion relationships, such as linear (doubling input doubles the size) or quadratic (doubling input quadruples the size). As far as I know, no image format - definitely not GIF - allows the recursive expansion necessary for such exponential growth.
With that said, GIF is a compressed format, and thus you can attempt decompression bombs with it. Formats that allow more dramatic compression will do better, but GIF might still do something interesting. There exist sites around the Internet, such as this one, which store decompression bombs for testing purposes. They have what they claim is a 100Kx100K GIF - which would take 10GB even at only 256 colors, if you tried to expand it to a bitmap - that is only 7MB (after removing the BZ2 compression). That's not a small image but it's not enormous; some sites will let you host bigger than that. Similarly, 10GB isn't an enormous amount of memory - many PCs and I think some phones have at least that much RAM these days - but it could certainly choke a lower-resource machine.


How can I confirm I'm vulnerable to OS X "rootpipe" (CVE-2015-1130)? I've read the disclosure post by Emil Kvarnhammar of TrueSec (Hidden backdoor API to root privileges in Apple OS X) and I'm trying to confirm whether I'm vulnerable or not.

After creating an exploit.py script with the contents of Emil's exploit POC, I run:

$ python exploit.py /bin/bash root-bash
will write file /Users/dserodio/root-bash
Done!

Then I can see that a suid root executable was indeed created:

$ ls -l root-bash
-rwsrwxrwx  1 root  Domain Users  1228336 Apr 14 10:51 root-bash

But when I launch this, it doesn't seem to be a root shell:

$ exec ./root-bash
$ whoami
dserodio
$ touch foo
$ ls -l foo
-rw-r--r--  1 dserodi  Domain Users  0 Apr 14 11:01 foo

If I use a shell script that runs id, creates files, etc. instead of using /bin/bash to create an interactive shell, the results are the same (ie.: created as suid root but apparently without root privileges).

Can someone help me understand what's happening, and if I'm vulnerable to the "rootpipe" bug (CVE-2015-1130)?

Your system is vulnerable since the binary is written. The reason you can't simply copy bash is because the written binary will be started with "real" user id dserodio and "effective" user id root. To switch to real user id root, the binary needs to call setuid(0). I've given a sample C code wrapper for this in the comments of my article you linked.

Another option is to copy /usr/bin/python2.7 to /tmp/py, and start /tmp/py. From there you can do 'import os' and experiment interactively with the python methods os.geteuid(), os.getuid() and os.setuid(0). After os.setuid(0) you can launch a root bash with os.system("/bin/bash").


Liquid security scenario I'm a part of a small team of undergraduate developers taking a course on developing Arduino and Raspberry Pi applications with a focus on the Internet of Things. Our current task is to imagine, design, and implement some useful system with the following requirements:

We must make use of a Raspberry Pi
We must use some external sensor or actuator in tandem with the Raspberry Pi
We must implement a web system supporting the physical device in some way

We've decided to make use of a magnetic valve to prevent unauthorized users from accessing a liquid. Use cases could include safely storing hazardous or poisonous liquids, preventing the theft of valuable liquids, or preventing minors from accessing alcohol.

To be more specific, we have connected our Raspberry Pi to the magnetic valve and to a number pad. When you enter a certain PIN, the valve opens temporarily to allow the flow of liquid and then closes after a fixed amount of time. This setup is considered one device.

We've developed a web system that allows a user with one of these devices to register an account with us. They are required to have a key located on the device to register an account. Once their account with us has been made, they can register additional devices if they have them. The user establishes a PIN for each registered device through the web system. They can use the web system to change their password for their web account, change PINs for any of their devices, and view reported logs of every time their device was successfully accessed.

Once a user has one of these devices and has registered online and established a PIN, their device is ready to dispense their liquid. The valve is attached to a very hardy container that locks into the mechanism, preventing an unauthorized user from simply removing the container of liquid from the device. Assume that the physical security of the valve itself, the container, and the locking mechanism are ensured for the purposes of this academic scenario.

When a user wants to access their securely stored liquid, they enter the associated PIN into a number pad attached to the Raspberry Pi. Their PIN is hashed and sent over the Internet to our server for comparison with the hashed PIN stored in our database. If the PIN is correct, the server returns to the device with a success signal. When the device receives a success signal the valve is opened for a fixed amount of time, set so that a certain volume of liquid will be dispensed before the valve closes once again. The server takes note of when the successful request occurred for logging purposes.

My problem is that the valve is opened and closed with two simple functions located on the Raspberry Pi itself. The application we've developed for controlling the device waits until it receives the success signal before opening and closing the valve, but I don't know how to stop a malicious user from writing their own application and making use of these two functions to open and close the valve.

The Raspberry Pi has both a video port and USB ports on the side. A malicious user that happens to be alone with the device could bring their own monitor and keyboard and hook up to the Raspberry Pi and run an application that could call the same functions that open and close the valve. How can I prevent this from happening?

Do I need the Pi to be secured physically so that the user can reach the number pad, but not the Pi itself? Is there a way to be to block the available ports from being used? Any suggestions as to how to handle this situation would be greatly appreciated. Security is not the main focus of this assignment, but I'd like to do the very best that I can.

Depending on your threat model you could add enclosures, alarms, CCTV, access controls to the room, a security guard etc... but without knowing what you want to do it is hard to say where to stop.

I would certainly consider securing the Pi itself - a locked metal container, securely fixed to the wall/device will make any attack harder/noisier/more obvious. Adding an alarm will also improve this.

If you can find an enclosure which incorporates a secure keypad (ie one that is hard to break and is tamper evident) that will help you prevent an attack.

Sealing ports can help, but if an attacker gets into the enclosure, they could access the traces on the PCB so while it has some deterrent value, I wouldn't recommend it.


Poor error handling source code review I received a report from the security team today. The report contains the below mentioned vulnerabilities and descriptions:

  1) Poor Error Handling: Overly Broad Throws

  The methods in program1.java throws a generic exception making it harder for callers to do a good job of error handling and recovery.

  2) Poor Error Handling: Overly Broad Catch

  The catch block at EXAMPLE1.java line 146 handles a broad swath of exceptions,  potentially trapping dissimilar issues or problems that should not be dealt with at this point in the program.

  3) Poor Error Handling: Empty Catch Block

  The method SomeMethod() in somefile.java ignores an exception on line 33, which could cause the program to overlook unexpected states and conditions.

After reading the report above, a few questions are raised in my mind:

How are these related to security? According to my understanding it seems like the above issues are code quality issues.
If those are real security threats, then how can an attacker exploit this?
What kind of protection controls are need to mitigate above issues?

I think you are correct that those issues are more related to code quality rather than security, and none of them are exploitable in any obvious way. I would not call them "vulnerabilities".

But vulnerabilities are born out of bugs, and bugs are born out of bad code quality. Bad error handling could lead to unexpected results - i.e. a bug - and if you are unlucky that could lead to vulnerabilities.

Here are some examples related to exception handling:

If you don't handle an exception at all, it could lead to the program crashing. This could be used for a denial of service attack - simply overflow the server with malicious requests that will crash it, and it will spend all it's time restarting instead of serving legitimate requests.
Unhandled exception might lead to disclosure of sensitive information, if error messages are passed on in HTTP responses (as pointed out by Rich Moss).
Overly broad catch statement that catch everything could lead to security critical exceptions being glossed over.

For real examples, check out this CVE list filtered on the word "exception" (as suggested by Ben Hocking).

The solution is to follow best prectices for exception handling. I will not cover that in detail here since that is more of a programming than a security issue.


Are the CPU protection rings meant to protect against malicious programs or against unintentional programming mistakes? I am trying to understand what is the purpose of the CPU protection rings (specifically user mode and kernel mode).

I don't think that the CPU protection rings are meant to protect against malicious programs, because a malicious program can be written to run in kernel mode instead of user mode (it can be written as a device driver for example) and then it will be able to cause whatever damage it wants.

I rather think that the CPU protection rings are meant to protect against unintentional programming mistakes, for example a programmer may unintentionally write code to access the memory of another process or the memory of the kernel, but since the program will run in user mode, the program will not be able to access the memory of another process or the memory of the kernel.

Am I correct?

Are the cpu protection rings meant to protect against malicious programs, or against unintentional programming mistakes?

CPU protection rings are meant to enable operating system software the control and protection checks necessary to implement an overall security strategy with good performance.  This includes the notion of kernel mode vs. user mode.  (Multiple rings are useful so that one operating system can efficiently guest host/run (an)other operating system(s), instead of only user programs.)

  I don't think that the CPU protection rings are meant to protect against malicious programs, because a malicious program can be written to run in kernel mode instead of user mode

You would still have to find an exploit that would trick the overall hardware/software system into running the program in kernel mode.  An operating system would be remiss in allowing an unknown program (from the internet or otherwise) to run in the most privileged ring, regardless of where that code might have wanted to run.

  (it can be written as a device driver for example) and then it will be able to cause whatever damage it wants.

Yes, if you could trick the system into loading your device driver, you'd have a lot of control.  Bootkits do similar, they bypass security by placing files early in the boot process, so that those run before the operating system has a chance to come up and protect things (then further, they hide themselves from prying eyes).

This an aspect of why permissions are so important.  A user mode program with unlimited permission can write to the file system in areas that will cause the operating system to load device drivers or the boot mechanism to load a bootkit.

  I rather think that the CPU protection rings are meant to protect against unintentional programming mistakes, for example a programmer may unintentionally write code to access the memory of another process or the memory of the kernel, but since the program will run in user mode, the program will not be able to access the memory of another process or the memory of the kernel.

Kernel mode, for example, can reprogram the hardware's virtual memory protection and mapping mechanism, and this allows an operating system to establish separate address spaces for user mode processes.  User mode, however, cannot make changes to the address space.  Yet, the hardware CPU cannot remember everything needed to maintain an address space, so when it runs into something it doesn't know about, it faults back into kernel mode asking the operating system software to take over — the OS then decides if this is an illegal access (e.g. at kernel memory, or some other process or shared library) or if this is a legal access that the CPU didn't fully know about this go around (this is how page faults work in virtual memory).

Ultimately, security is accomplished by a complex choreography between hardware and (operating system or privileged) software.  The hardware does simple (and a few complex) things that it can be programmed to do and that it can do rather quickly (perhaps in parallel with other computing), and anything that either doesn't fit inside the CPU or is overly complex is left for software.  Software then makes use of the hardware features constantly changing and reprogramming the hardware as needed to run different programs or even different parts of the same program, while preventing the program from coloring outside of the lines.


Token contains a reflected XSS vector in the  tag error in Chrome We have a web app and we send the back URL through post to various pages to enable users come back to the parent.

The double quotes are translated to &quot; to avoid XSS and then translated back. The final tag is like this - form name="back_url" action="server side script" method="post".  These double quotes are creating the "Token contains a reflected XSS vector"  error. Once I remove the double quotes like form name=back_url action=server side script method=post , the back button works. This issue is only in Chrome. Not sure how to resolve this.

You should use URL encoding not HTML encoding. If you URL encode the back_url parameter the quotes shouldn't trigger any XSS warnings and you won't need to deal with converting them back and forth to make the redirect work correctly.

Also be wary that this design introduces an open redirect vulnerability into your application. An attacker can craft a URL for your website that redirects to an attacker controlled site when they use the back button if you're not properly sanitizing the back_url parameter.


How can I prevent myself from barcode payload attacks? Recently I came across a tool which can inject payloads into a barcode. How can I prevent myself from this kind of attacks?

Attack scenario:

The attacker prints vulnerable barcode / sends vulnerable barcode to me
I scan the vulnerable barcode and the payload attacks my system
The attacker gains access

Possible preventive scenarios:

Never scan barcodes - but it's not easy in terms of departmental stores or any company storage areas (where barcode scanning is important)

Apart from the above any possible preventive solutions in order to prevent this type of attacks?

After going through the code, I'm not sure that it is supposed to exploit or attack anything. It looks like its only purpose is to encode a payload using barcodes. It would be a nice way to import code into a system using a barcode reader when all other routes may be blocked. After you locate a vulnerability in a system, you can "upload" a payload using one of the these barcodes.

As such, there is nothing to defend against. It is getting the bar code scanner to do exactly what it is supposed to do: convert a barcode into text.


Securely redirecting to a different domain with sensitive information I have a scenario where users logging in to one site are redirected to another domain, logged in there as well, and then redirected back to my main site (so that logging in to one allows them to log in to both). We will be including some kind of token with the login to authenticate the request. Both sites have valid SSL certificates.

My two concerns are:

1) Since redirects must use GET instead of POST, how can I send the token without it being exposed in the url?

2) The url I'm redirecting to is using HTTPS, however I know from asking this question (How to ensure my API requests are sent using SSL) that SSL can be compromised if you don't verify the certificates on both ends of the request. How can this be done for a redirect?

I'm using PHP and Laravel. I'm very much a beginner when it comes to web security, so I apologize for the basic questions. If this isn't the proper stack exchange for this question, please let me know and I'll remove it. Thanks!

Since redirects must use GET instead of POST, how can I send the token without it being exposed in the url?

Redirects can actually use POST (redirect code 307) but since POST is considered a state-changing operation contrary to GET it should not just be repeated without asking the user. Best would be if it does not matter when the token gets visible, i.e. it can be encrypted by the origin site and decrypted by the target side. This can be done for example with public key cryptography if the origin knows the public key of the target.

  however I know  ... that SSL can be compromised if you don't verify the certificates on both ends of the request.

This statement is not true and it is not claimed in the question your reference. For securing a SSL connection against man in the middle attacks it is only needed that the server authenticates itself with a certificate and the client properly validates this. Client certificates are only needed if the server likes to authenticate the client but are not needed for protection against a man in the middle.

There is no special thing to watch out with redirects and HTTPS in your case: the client simply does TLS to both sites and validates their certificates.


during ssh handshaking server introduce itself - does it improve security to change self presentation? My Archlinux running devices does not present themselves duing ssh handshake:

$ telnet 192.168.1.151 11735
Trying 192.168.1.151...
Connected to 192.168.1.151.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4

However Raspribian

# telnet 1.2.3.4 1234
Trying 1.2.3.4...
Connected to 1.2.3.4.
Escape character is '^]'.
SSH-2.0-OpenSSH_6.7p1 Raspbian-5+deb8u3

or Ubuntu Server 16.04 LTS

# telnet 4.3.2.1 4321
Trying 4.3.2.1...
Connected to 4.3.2.1.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1

They introduce themselves during handshake.

Does configuring system to not present themselves during handshake, increase security?

(I guess, it does, as knowledge about software and version allow to narrow search of potential security holes)

If, yes, how to configure server to not introduce it's OS version during ssh handshake? (or maybe even introduce as some other, to confuse potential adversary?)

Does configuring system to not present themselves during handshake, increase security?

Yes, service fingerprinting is a first step for an attacker to identify vulnerable systems. It's good advice to not advertise version details of your OS.

  how to configure server to not introduce it's OS version during ssh handshake?

In /etc/ssh/sshd_config you can set the VersionAddendum entry to none or a custom vaue:

VersionAddendum none

(Make sure you restart the SSH daemon afterwards.)


Risks and strategies to implement anonymous storage of Google Cloud Messaging tokens? I'm writing a mobile app that aggregates weather data and generates a push notification when certain criteria are met. The user has the option to change some of the variables (e.g. if the current temperature exceeds X degrees) which is stored both on the device, and on my server.

When my app opens, it requests the GCM (or APN) token and the user-defined variables and sends them to my server via POST. The endpoint would look something like this (if it were a GET):

https://api.example.com/registerPush.php?key=gcm_key_here&maxtemp=80&type=android

(obviously type would be apple if it were an iOS device)

On the server end, registerPush.php takes the variables and stores them (via prepared statements) in a MySQL database. The requester is allowed 1 registration per 10 seconds (determined via PHP sessions) and if they exceed that, they get locked out for 2 minutes, to avoid one user trying to spam the database with bogus entries.

Every hour, a cron job runs and loops through all the items. If the temperature exceeds maxtemp, the token is added to an array, and bulk-sent to those users via the correct push method (e.g. GCM or APN).

I'd like to keep this system "anonymous" (that is, not require a user to sign up), because creating an account simply to store push notifications is a bit overkill for the simplistic nature of my app, and things such as "Login with Facebook" are the same, because why should a user sign in with Facebook, just to get push notifications?

So my question is, short of throttling registration attempts via $_SESSIONs, and perhaps storing the last time the token was sent to the server (and clearing out old tokens after X many units of time), what can I do to make this system more secure, short of asking people to create an account (for a simple weather app)?

I would suggest using String m_androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

This will give you a unique ID, that require no permissions, that does only change during factory reset, and can be used to track so nobody spams the database. I would also suggest hashing with a app-specific key.

However, you still need to have any throttling to prevent someone from creating malicious entries. A good idea could be requiring the solving of a captcha to submit a "new" ANDROID_ID string that does not exist in database. This can be solved with a WebView and using Google Recaptcha, upon first launch of the app, combined with IP-based throttling.

Do remember that many cellular operator NAT's lots of customers behind one IP, so guard the logs carefully and if you see the app being popular and be prepared to increase the throttle limits incase your app start being more popular.

This could be implemented automatically by having a AI, that will compare the median request rate for all IPs to a specific rate, and only block if the rate is considered higher than this.
Median request rate is in other words, the request rate that is the average of the request rate of all IPs, but with the "low-balls" and "high-balls" removed.


Why Software Configuration Management tools (SCMs) authenticate only client instead of server? I've noted that probably all of the 4 popular Software Configuration Management Tools (SCMs), ie.:

Puppet,
Ansible,
Chef,
Salt

use only clients' authentication instead of the server authentication –  correct me if I'm wrong (I suspect I'm wrong, but I don't know why).

Why is that? Isn't it unsafe to trust the server that in fact manages nearly every detail of the clients' system configuration?

Here is description of how Puppet's authentication is provided. Isn't it possible for an attacker to run MITM attack by pretending to be Puppet server? Does authenticating clients by the server somehow provides mutual authentication?

Here is description of how Puppet's authentication is provided.

The link you provide clearly says:

  Communication between the master and agents is granted and secured with client-verified HTTPS, which requires valid identifying SSL certificates.

Given that some kind of server authentication is always done with HTTPS this only means that client authentication is done additionally to server authentication and not that only client authentication is done.


The Perfect Mousetrap - Can a sandbox system be designed such that it's identical to an actual computer? In testing suspicious files for malware, the typical method is to search for known malicious code. This is why zero-day malware attacks can be so dangerous — their malicious code is previously unknown to antivirus software. The ideal solution is to test every file and program in a sandbox before it is used, and this has been tried, but as far as I know, typically unusual processes appear that can be detected by a smart enough mouse. The malware detects that it is being sandboxed, and holds back on its malicious behavior to keep from being discovered.

The question is, can it be possible, and more importantly practical, to build a sandbox that's identical to an actual computer, and then implement in today's operating systems (Windows, OS X, Linux, iOS, Android) a software which which uses it to test everything before it is run, or even better, uses it as the running environment for that file?

Yes, it can be done as (theoretically) every "computing device" is computationally equivalent to every other computing device. Look up the Church-Turing thesis if you are interested.

However your question is grounded in practice and in this case the answer is "yes, but it would cost too much". Effort in virtualisation today aims at speeding up the virtual environment as much as possible to the point where it is quite trivial to detect if you are running in a virtual machine. Which means that any effort in replicating a system running 100% "native" is limited by the number of people with your same interest.

In other words there is very little commercial interest in doing what you are aiming for and the ROI would be limited only to the few hobbyists and companies that have a vetted interest in the matter. How much would you pay for such system? How much time can you devote? How many people do you know that are willing to spend years on this project?

While there are efforts to research this I haven't yet seen a fully working system that's not terribly slow. For example, Skype employs anti-debugging techniques that detects slowdowns (see slide 30 of this presentation). I suspect any malware could do similar tricks to measure execution against a fixed time server and detect when it's running in a (necessarily slow) emulator.

I think that a different approach would be more economically sound: run the malware sample on an actual machine, and observe what happens. Then "ghost" its disk and memory and look at the differences with an identical, "clean" sample. It might take less time to do, overall, than developing a simulator like the one you have in mind.


What are hashes that begin with $1$...? I've found this hash and I'm wondering what is it.

$1$h6k3X5db$pp8WQ5R5YYL5bNyQj2wP70

If that was produced by crypt(3) then it is an MD5 hash.

  If salt is a character string starting with the characters
        "$id$" followed by a string terminated by "$":

        $id$salt$encrypted

  then instead of using the DES machine, id identifies the
  encryption method used and this then determines how the rest
  of the password string is interpreted.  The following values
  of id are supported:

         ID  | Method
         ─────────────────────────────────────────────────────────
         1   | MD5
         2a  | Blowfish (not in mainline glibc; added in some
             | Linux distributions)
         5   | SHA-256 (since glibc 2.7)
         6   | SHA-512 (since glibc 2.7)


Speed of key generation - Is old hardware safer? I'm currently generating a new gpg cryptographic key, and I'm using a new laptop for this. I can notice that the key generation step, which involves the random generation, is extremely quick, while I can recall that, on my old laptop, this process required a certain amount of time.

For a normal operation this should be reasonable, as I'm working on a more recent computer, but for this operation I would expect that much more time is needed. The software asks me to "type on the keyboard, move the mouse, utilize the disks", but everything terminates before I can do anything.

Yes, probably there's some other source of entropy besides the user input, and I don't know which one are taken in account by the kernel. But to be sincere, in the light of the recent revelations about global surveliance, I became even more paranoid, and the idea that my brand new laptop could be tampered by design to yield weak random cyphers popped out of my mind.

So the question is: is it safer to generate the keys using old hardware?

New laptop, new software. For proper randomness, enough entropy must be gathered from hardware events, but nothing forces this gathering not to begin before the launch of the key generation process. In modern operating systems, the OS kernel is the piece of software which gathers hardware-related data, and it centralizes this process. Once sufficiently much entropy has been gathered (roughly speaking, at least 128 bits), it suffices to extend it with cryptographically secure PRNG, and you will get randomness by the megabyte (at least, pseudorandomness computationally indistinguishable from true randomness, and that's good enough for cryptography).

In Linux terms, this is the difference between /dev/random and /dev/urandom. Possibly, the OS and GnuPG version you have on your new laptop do the sensible thing and use /dev/urandom, while the previous version indulged in some weird but widespread randomness fetish and irrationally insisted on "true randomness" for some notion of "true".

Be assured that if your laptop hardware and software had been tampered with, you would not notice it with something as crude as faster key generation. Competent spies know better.


two websites with same signing cert but google chrome says CA is invalid for one of them and not the other? I have two websites:

[redacted]
[redacted]

When I visit the first one with Google Chrome 57.0.2987.98 I get a "ERR_CERT_AUTHORITY_INVALID" error. But the second website gives me no such error.
I exported the top level CA cert in the cert hierarchy and did a binary comparison between the two. They're the same certs. So why am I getting this error?
The first site is using a wildcard domain. Is that the issue?

StartCom certificates are no longer trusted by Chrome, due to a number of irregularities found in WoSign (the parent company of StartCom) and StartCom's certificate issuance practices.   There is a blanket policy of distrusting all certificates issued by WoSign or StartCom after October 21st, 2016, but due to a requirement for certificate transparency and other unspecified technical reasons, certificates issues before this date may not be trusted either.   Since the certificates for both of the sites you referenced were issued before this date, it appears that one of them meets Google's criteria to remain trusted, while the other does not, for indeterminate reasons.

You can read more about Google's decision to stop trusting certs signed by these roots here.


Homebrew and NOPASSWD sudo I like to be able to run some commands installed via Homebrew without typing my sudo password. The problem is that Homebrew installs everything with user permissions, so if I add the executables to sudo's NOPASSWD list (via user ALL = (ALL) NOPASSWD: ...), these files can be replaced and so any arbitrary program can run as sudo. chowning the executables would also be problematic, as it will break Homebrew's update mechanism. Homebrew can't be installed on the root account either. What should I do?

So, either you find a mechanism to find all the executables that you want to be able to run as root, or allow your user to run everything as root:
user ALL=(ALL) NOPASSWD: ALL

Run this from cron and use the output to update a file in /etc/sudoers.d.
If you want to be sure that a program is not updated by the user, install using a separate homebrew user. In that way, your user is not able to change the programs (only the user homebrew can update the programs and all programs are owned by him).


Preventing socket.join("room") client-side, listening for private room leaving i'm developing an application with Socket.IO that needs to authenticate if user can join a room.

Client side:

var socket = io('http://<?php echo $_SERVER['HTTP_HOST'];?>:3000');
socket.on('connect', function() {
    var req = [current_user_id,secret_hash];
    socket.emit('join', req);
});

Server listens on join requests of clients, gets access to a MySQL database and evaluates if user can join or not the requested hash channel:

        ...
        if (rows.length == 1) {
            socket.join(request[1]); //join on channel ID which is request[1] cell of array
        }
        //if not authorized, does not allow joining.
        ...

I've got two questions:

1) I don't want to allow client side direct joning of channel. Clients must not be able to launch socket.join("room"). How can i block those requests? Server is the only one that cares about assigning rooms.

2) Is there a way to listen for event "user leaves his private channel id"?

Thanks.

The client-side socket.io library does not have the ability to .join() a room.  That ability is only in the server-side library (because that's where the rooms are maintained) and thus the only place it can actually be processed.

So, the only way to join a room is to make your own message for a join request from client to server and process that message on the server on behalf of a given client which enables you to do any sort of checking you want before any client can join a particular room.  As such, you should be safe the way you're already doing it.

Similarly, there are only two ways that a client leaves a room.  The first is when you process your own message and call .leave() server-side so you can certainly monitor any time that happens since it's your own server-side code calling .leave().  The other way a client leaves a room is when the client disconnects and you can also monitor for disconnects in the server.  Like with .join(), the client cannot call .leave() directly so you don't have to worry about that.


How would I go about rebuilding the IAT of a packed executable? When executables are packed with a tool such as UPX, the real code and data sections are encrypted or obfuscated, then loaded into memory using an injected decrypter stub. This makes static analysis impossible.

In order to circumvent this, I would normally run the executable, attach a debugger, take a memory dump, then use that dump to produce an unpacked executable. Unfortunately, this destroys the import address table (IAT).

I'm aware of certain tools that can be used to patch the IAT, but I don't know how they work internally. How would I go about manually recreating the IAT?

Ok, I said I would go for an answer and here it is, as promised.

Firstly, I wanted to build an actual target to play with. There's nothing like a working, touchable example, and this is very much a manual process. So, without further ado, I compiled this in MSVC with /MT:

#define WINVER 0x501
#define _WIN32_WINNT   0x0501
#define _WIN32_WINDOWS 0x0501
#define _WIN32_IE      0x0501
#define UNICODE

#include <wchar.h>
#include <windows.h>

int APIENTRY wWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    MessageBox(NULL, L"Hello, world.", L"A messagebox", MB_OK | MB_ICONEXCLAMATION);
    return 0;
}

We'd fully expect this beasty to import user32.dll!MessageBoxW and sure enough it actually does.

To find this inside the executable itself, let's use WinDbg. I use WinDbg for two reasons: firstly, I can't afford IDA, and secondly, it's the same debugger you'd use for a kernel driver (even with IDA - which uses its engine) so it's good, if a little unintuitive.

I compiled my executable to UnpackSimple.exe for the x86 architecture, as UPX doesn't support Win64. Now, the first thing you'll notice when you run this under WinDbg is this line:

ModLoad: 01360000 01370000   UnpackSimple.exe

Right there, we see the address range to which UnpackSimple.exe has been mapped. This is important, because all addresses in its header are relative to 01360000.

So now, to find the header information, we can simply request it:

!dh UnpackSimple.exe
OPTIONAL HEADER VALUES

    10B magic #
   11.00 linker version
    5E00 size of code
    6C00 size of initialized data
       0 size of uninitialized data
    1193 address of entry point
    1000 base of code
         ----- new -----
01360000 image base            <--- this is the image base address.
    1000 section alignment
     200 file alignment
       2 subsystem (Windows GUI)
    6.00 operating system version
    0.00 image version

    ... blah blah blah ....

   0 [       0] address [size] of Export Directory
8D54 [      3C] address [size] of Import Directory
D000 [     1E0] address [size] of Resource Directory
   0 [       0] address [size] of Exception Directory
   0 [       0] address [size] of Security Directory
E000 [     6D0] address [size] of Base Relocation Directory
7150 [      38] address [size] of Debug Directory
   0 [       0] address [size] of Description Directory
   0 [       0] address [size] of Special Directory
   0 [       0] address [size] of Thread Storage Directory
89D8 [      40] address [size] of Load Configuration Directory
   0 [       0] address [size] of Bound Import Directory
7000 [     108] address [size] of Import Address Table Directory
   0 [       0] address [size] of Delay Import Directory
   0 [       0] address [size] of COR20 Header Directory
   0 [       0] address [size] of Reserved Directory

Oh look, one IAT! It lives at 01360000+7000 and we can persuade WinDbg to provide us that information in a fairly straightforward manner. The dps command we are about to use is short for dump pointers, dereferencing with symbols, it takes an argument address and a space per entry address.

dps 01360000+7000 L108/4
01367000  75b3d7ea kernel32!TerminateProcessStub
01367004  75b23f3c kernel32!CreateFileWImplementation
01367008  75b2520b kernel32!GetCommandLineWStub
... <snip> ...
013670f4  75b47ab2 kernel32!WriteConsoleW
013670f8  75b21410 kernel32!CloseHandleImplementation
013670fc  00000000
01367100  76bafd3f USER32!MessageBoxW
01367104  00000000

You can see some important features of the IAT here. First up is the address on the left hand side - IAT entry address. The address on the left is the in-memory address for the DLL. Finally, note there are some zero entries. Each DLL import ends with a zero entry, telling the loader that there are no more entries to load.

Now, we shall look at the disassembly of the main function. To do this, type these two commands

bp UnpackSimple!wWinMain
g

You'll then break on entry to the wWinMain above. Now, if you look closely:

UnpackSimple!wWinMain:
    01361000 6a30            push    30h
    01361002 68a0893601      push    offset UnpackSimple!`string' (013689a0)
    01361007 68bc893601      push    offset UnpackSimple!`string' (013689bc)
    0136100c 6a00            push    0
    0136100e ff1500713601    call    dword ptr [UnpackSimple!_imp__MessageBoxW (01367100)]
    01361014 33c0            xor     eax,eax
    01361016 c21000          ret     10h

Unsurprisingly, there's our function, _imp__MessageBoxW, referencing a nice IAT entry :)

So now the question is how on earth do we go backwards? Well, to first build something that just doesn't work, we need to get hold of a packed executable.

To that end, I ran upx.exe -o UnpackSimplePacked.exe UnpackSimple.exe to produce a nice packed binary. Load this binary up in WinDbg and the first thing you'll notice is that:

!dh UnpackSimplePacked.exe

Does absolutely nothing. However, we can note that:

ModLoad: 01220000 01233000   image01220000

has been seen - so the image we need is there, in memory. It just doesn't exist as an on disk image. At this stage, I am guessing that upx actually loads DLLs directly itself, rather than using the NT Loader. We can prove this two ways: firstly, if you type sxe ld into WinDbg, it'll break on all module loads. No breaks occur for user32.dll, nor is it loaded already.

Secondly, as you wanted to see:

    0 [       0] address [size] of Import Address Table Directory

It's completely empty.

However, if we check the loaded modules list:

lm
start    end        module name
00210000 00223000   image00210000   (deferred)
74c20000 74c2c000   CRYPTBASE   (deferred)
74c30000 74c90000   SspiCli    (deferred)
74d80000 74e20000   ADVAPI32   (deferred)
74eb0000 74f4d000   USP10      (deferred)
74f50000 74f5a000   LPK        (deferred)
75030000 750dc000   msvcrt     (deferred)
755a0000 755b9000   sechost    (deferred)
75720000 757b0000   GDI32      (deferred)
757e0000 758d0000   RPCRT4     (deferred)
75b10000 75c20000   kernel32   (deferred)
76ab0000 76af7000   KERNELBASE   (deferred)
76b40000 76c40000   USER32     (deferred)
77550000 776d0000   ntdll      (pdb symbols)

As you can see, USER32 has space allocated ready to go.

Now here's some trickery. I opened up another WinDbg Window with my UnpackSimple.exe version and found the address of user32!MessageBoxW. Having got this, I found it to be 76bafd3f from a base offset of 76b40000 giving me an offset of 6FD3F. In my packed version, I set a breakpoint on bp 76b40000+6FD3F and sure enough, there was a stack trace!

k
003cfd0c 013a1014 USER32!MessageBoxW
WARNING: Stack unwind information not available. Following frames may be wrong.
003cfd6c 75b233aa image013a0000+0x1014
003cfd78 77589ef2 kernel32!BaseThreadInitThunk+0xe
003cfdb8 77589ec5 ntdll!__RtlUserThreadStart+0x70
003cfdd0 00000000 ntdll!_RtlUserThreadStart+0x1b

The dissassembly at the location in image0... looks like this:

013a100e ff1500713a01    call    dword ptr [image013a0000+0x7100 (013a7100)]
013a1014 33c0            xor     eax,eax
013a1016 c21000          ret     10h

Now we're getting somewhere! At that address you'll find some interesting data:

db 013a7100
013a7100  3f fd ba 76 00 00 00

Funnily enough, there's our address! 76bafd3f in good old little endian. Let's step back a bit:

db 013a7098
013a7098  a0 22 57 77 60 22 57 77-c9 14 b2 75 ff 10 b2 75  ."Ww`"Ww...u...u
013a70a8  7b 44 b2 75 9c 17 b2 75-91 d1 b4 75 71 51 b2 75  {D.u...u...uqQ.u
013a70b8  45 49 b2 75 c4 d1 b4 75-13 49 b2 75 b3 d1 b4 75  EI.u...u.I.u...u
013a70c8  46 e0 57 77 f1 24 59 77-0d 17 b2 75 46 19 b2 75  F.Ww.$Yw...uF..u
013a70d8  2a 30 58 77 61 48 ba 75-83 46 b2 75 07 7c bc 75  *0XwaH.u.F.u.|.u
013a70e8  28 13 b2 75 bf 45 ba 75-ef c7 b3 75 b2 7a b4 75  (..u.E.u...u.z.u
013a70f8  10 14 b2 75 00 00 00 00-3f fd ba 76 00 00 00 00  ...u....?..v....

I see pointers!

This is the IAT we found previously, or at least an array of IMAGE_IMPORT_DESCRIPTOR thunks.

So having got this far, what remains? Well, we'd need to search through the dumped memory to try to find functions which match known Windows DLLs. From there, we can begin to reconstruct a full IAT for our new PE file. I suspect the process ImpRec goes through, as described in Viv's answer is to attempt to find these entries as I have done manually. I've chosen to use breakpoints, but there are a number of ways this could be automated differently, I imagine. I've never written an automated tool to go through the process by hand...! That said, at a guess hoovering up call ptr instructions, looking at their entries outside of a mapped region then attempting to find those against known DLL offsets would do the trick.

Two notes:

I've written this answer as a "here's how I'd attack it manually" type answer, with relevant background, not a "use this tool".
Watch out for ASLR. Those module addresses will keep shifting around, so keep an eye for changing module bases!


Why is it a bad idea to escape HTML before escaping SQL? From the security perspective (and not usability as it's discussed here https://stackoverflow.com/questions/3648430/is-it-a-bad-idea-to-escape-html-before-inserting-into-a-database-instead-of-upon), why is it a bad idea to escape HTML before escaping SQL?

With regard to database security, it's irrelevant. SQL doesn't care if the string contains raw HTML or escaped HTML or whatever.

But as explained in the other question, this messes up the data. I would actually consider it a bug.


How to authenticate a specific client program? I have a server application which provides functions to a client program. The client is also programmed by me. Now I want to authenticate the client program itself (not any user) before using my service. I want to achieve that my service can only be used by executing my client software. The problem is, that both server and client aren't necessarily connected to the internet. Therefore, any authentication via a third entity cannot be used.

In my opinion, some secret has to be compiled into the executable of the client program and something like a challenge-response-procedure has to be performed.

What do you think about this thought or do you any have other ideas?

I've already thought about a client certificate but the certificate itself has to be compiled into the executable, too.

Thanks in advance.

You cannot ensure that the program talking to the server is your program. Anything client-side can be compromised, and any communication coming from the client can be altered.

The multiplayer game industry is facing a decades old battle against the kind of problem you stated, and even with millions in funding, expert programmers and a lot of money at stake, they cannot prevent people from using custom client software to interfere with their systems.

  some secret has to be compiled into the executable

And the attacker can extract this secret, reverse-engineer the challenge-response protocol, and write its own client.

  thought about a client certificate

It won't work. Attackers can extract the certificate and misuse it, like the secret.

You can obfuscate the code, add certificates, add secret data, checksums, and any client-side measure, they will not prevent a dedicated attacker from writing its own client if he has enough incentive.


Are there state-of-the-art techniques or theory specifically for attacking passphrases over passwords? With passphrases becoming more and more common based on length being more important than complexity, I'm assuming there must be some work going on involving techniques aimed specifically at cracking / auditing passphrases which would differ to some degree from the traditional methods for attacking passwords, perhaps involving Natural Language Processing, grammar, syntax, stemming, etc.

I realize there are different kinds of passphrases and that those invented by humans should be more susceptible to attack than those randomly selected from set wordlists such as suggested in a recent XKCD web comic.

Are there some resources I can read on the web to get myself up to date on what people are trying and having success with?

I don't know how "state-of-the-art" this is, but the password recovery software Passcape uses a dictionary attack against passphrases.  This is very similar to a simple brute force character-permutation attack against a password, except permutations of dictionary words are used instead (once common phrases and quotes from movies, books, and poems are exhausted).

As it says in the linked article:

  It wouldn't be an overestimation to say that 99 percent of the success in the recovery of a password with a dictionary attack depends on the quality of the dictionaries.

As such, it seems like a simple defense against this type of attack would be to include words that wouldn't appear in any dictionary.  Mis-spell words, leave out vowels, substitute letters, etc.


Cheating or service disruption by altering client-side code A reasonably white-hatted hacker has demonstrated the ability to insert text of his own choosing into the communication between a java applet and a web based server.  Not a simple MITM attack, but using a tool like "JavaSnoop" to tap into the communications within the java applet class structure.

I believe that there is ultimately no defense against this kind of attack (and here I would welcome being contradicted) - he could in principle substitute an entire client of his own choosing; and of course the server has to be armored against all manner of malicious  inputs.

The canonical example of this would be cheating in an online game by altering the client or the communications between client and server.

Is there anything better than security by obscurity to make this process as difficult as possible?

JavaSnoop is a tool for exploiting vulnerabilities such as CWE-602: Client-Side Enforcement Of Server-Side Security. Even thick clients cannot be trusted, and if a distributed system exposes sensitive functions to thick clients,  then that is a vulnerability.   There is no point in defending against "JavaSnoop" or even "Firebug" or "burp",  these are just tools.  The system as a whole needs to be taken into consideration, and a server must be vetted for remotely exploitable vulnerabilities that are accessible though any means.

The process for enumerating these types of vulnerabilities is no different than any other vulnerability.  An assessment team,  or penetration tester will look at exposed functionality and test this functionality for common vulnerabilities such as SQL Injection,  or trust boundary issues.


Man-in-the-middle attack over an encrypted channel I learned recently about man-in-the-middle attacks and came up with this question.

Let's say we have two computers who try to communicate over the network. Each computer has an encryptor and a decryptor.
Also let's assume that the ciper used by the two computers is unbreakable and that the computers use a pre-shared key.

For example, if we send packets from one computer to another, it will first get encrypted by the first computer's encryptor and then get decrypted by the other one's decryptor and so on.

Is a man-in-the-middle attack possible here? If so, how can we do it? Consider the fact that the data is encrypted on both sides.

How we can protect ourselves in this case?
Is it possible to sniff packets over this communication in other ways?

Terminology: a secure channel is a communication channel that is protected against man-in-the-middle attacks and eavesdropping. Encryption alone does not make a secure channel. The simple way to establish a secure channel is to use SSL/TLS. but there are subtleties.

Encrypting the traffic is only part of the protection against man-in-the-middle attacks. This prevents the attacker from decoding the traffic, because he doesn't know the decryption key. This also prevents the attacker from injecting arbitrary traffic, because he doesn't know the encryption key.

With only encryption, the man-in-the-middle can inject some traffic by coming up with some ciphertext. He might not know what the plaintext is, but that can still cause trouble — the recipient is getting garbled data, which could even trigger a parser bug. A secure channel provides not only encryption, but authentication — a verification that the data comes from the legitimate source.

If the communication protocol is based on packet, each packet must have a tag that indicates who sent it (so that the attacker can't send traffic from one party back to itself) and some kind of sequence number (so that the attacker can't resend an old packet, which may now have a different effect).

Of course, if the attacker can suppress traffic in addition to listening and injecting, the attacker can disrupt the communication by cutting it off altogether, reordering packets, etc. Reordering packets can be detected (and the packets reordered or discarded) by properly using sequence numbers to authenticate the communication (which is stronger than authenticating each individual packet). No amount of cryptography will remove the attacker's ability to block all traffic, if he can delete packets. You need physical means: armed couriers, radio transmitters that are stronger than the adversary's jammers, …

Encryption might not always ensure that the communication remains confidential. The communication may allow side channels. In particular, the size and timing of packets may be revealing. For example:

If on 5 June 1944 the BBC had suddenly transmitted a flurry of coded messages, that would have indicated that something was afoot, even if the messages had been undecodable. Remedy: send coded messages all the time, and if you have nothing to send, send random messages that are indistinguishable from useful messages.
The size of the message may be an indication. For example, if military orders are sent to a rnpwbhm instead of a mcouzjooyb, you would know that the scope is important enough to involve a captain rather than a lieutenant, even if you wouldn't have been able to decrypt the rank. Remedy: use fixed-length codes for related concepts; dually, randomly vary the length of potentially-recognizable terms (e.g. through variant spellings of proper names, or more systematically append random-length garbage). (Both the attack and the remedy I cite here are from WWII histories, though I don't have the reference at hand.)
Voice traffic is particularly vulnerable to reconstruction because it is typically compressed and sent in real time. The rhythm of packets alone can be enough to reconstruct speech in lab conditions. Remedy: compress less and accept more lag, for example send a fixed-size packet every N milliseconds.

Another difficulty with protecting against man-in-the-middle attacks is initiating the communication. With a pre-shared key, this is not a problem, but if the two parties don't know each other beforehand, the attacker could be a direct man-in-the-middle: when Alice tries to establish a channel with Bob, Eve intercepts all packets and lets Alice establish a channel with her, then she establishes a channel with Bob, and relays traffic or not as she pleases. This is why SSL requires a certificate verification: the client verifies that the channel it's setting up is to the desired server (and, optionally, the server performs the symmetric verification).


MITMf arp spoofing inconsistent using MITMf I'm getting inconsistent results, sometimes it just works, other times it just doesn't... I'm wondering is it like that for others or am I doing something wrong?

the command I'm using just for arp spoofing no injecting or anything is:

python mitmf.py --log-level debug -i wlan0 --spoof --arp --gateway 10.0.0.138 --targets 10.0.0.1

It will often get stuck after printing

Http server online
DNSChef v0.4 online
SMB server online

It just stays there and nothing happens.
Then I'll run the same command again and it seems to work, what changed?

also sometimes on the victim browser, it takes a long time to load a page, or it won't load at all but when it freezes on attack computer, on victim computer the pages load fast again... When it's working I usually have to refresh the page on the victim computer a few times..

on attacker computer I get

[ServerConnectionFactory] Server connection failed.
[ServerConnectionFactory] Retrying via SSL
[ServerConnectionFactory] Server connection failed.

but it starts working again..

Is this normal or something wrong?

Thanks....

apt-get install mitmf

now that works

mitmf --log-level debug -i wlan0 --spoof --arp --gateway 10.0.0.138 --targets 10.0.0.1


Considerations for information exchange agreement between governmental agencies Question: When drafting an information exchange agreement between governmental agencies what security related sections should be considered for inclusion? Example agreements?

What is the security perspective of an information exchange agreement? Unfortunately my research into the subject have revealed close to nothing in useful guidance. Section 6.2.3 (Addressing security in third party agreements) in SS-ISO/IEC 27002:2005 is not entirely helpful.

In addition to the ISO-documentation I've read several Information Exchange policies, but none seem to include an actual agreement. Mostly it seems to revolve around the following sections (specific details remain hidden from view):

Use an "endorsed" information security management system (ISMS)
Establish roles and responsibilities
Confidentiality, integrity and availability requirements (... doh)
Business continuity plan
Incident procedure/processes

Would appreciate any guidance, experience or knowledge you might have to share pertaining to my question. At this point in time almost anything is better than what I have which is close to nothing. (Points for examples!)

In my experience in high level agreements of any type it's very difficult to insert specific requirements relating to security due to the challenge of matching controls that different organisations have in place (i.e. trying to get the other party to state compliance against your specific standards)

That's why most times, you'll see language around things like ISO2700x ISMS' .  These form a common base where someone can say that the other party has a "reasonable" level of security in place (with the usual caveats that apply like the scope of the ISMS matching the use of the data etc)

Apart from that I'd say that the main security requirements you could consider would depend on how much you know about the specific data being shared under the agreement.

If you know for example that one class of data that's being shared should only be used by a specific department or individual in the other government that's something that would be worth adding to the agreement.

Also having a mapping of terms relating to things like protective marking could be useful to ensure that there are no mis-understandings relating to the information shared.


How is a message verified from a hashed and encrypted version of the message? My understanding till now  is that when a message is hashed, it cannot be reconstructed back from the hash.

When the hash is calculated and sent along with message, the attacker can change the message as well as calculate the new hash. And send the new message and the new hash to the receiver. So how are authenticity, integrity   achieved?

Hash is only used for integrity check.
First you encrypt the plaintext using session keys and then compute the MAC of cipher text.
So you send (CipherText, MAC_Of_Cipher)
On receiver side, we compute MAC of Cipher text(using MAC Key) and if both received MAC and calculated MAC matches, message is authentic and we proceed to decrypt the message.

MAC provided authenticity as well as integrity of message while hash only provide integrity check.

Session keys and MAC Key are generated at both ends  while creating secure tunnel like TLS.


Does setting httponly prevent stealing a session using XSS? If a session token is stored in a cookie that has httponly set, is there any way that a XSS vulnerability could allow a malicious user to steal a users session token?

In general, if httponly is set on its token then an XSS attack shouldn't be able to retrieve a session token. Modulo past bugs in browsers and plugins, and server misconfiguration (eg responding to HTTP TRACE).

But it's not worth much. You can stop XSS from getting hold of the token, but an XSS attack still has full control of the session on the user's machine: it can force the user to do pretty much anything on the site, or falsify the user's interface to the site (eg to phish for site credentials). See BeEF for an example of what an attacker can achieve with a compromised session: you've pretty much lost already.

Not setting httponly at best makes life slightly easier for the attacker in that they can access the session from their own machine in their own time, rather than being limited by the amount of time the user keeps their browser window open. It's worth having httponly where possible, but it's a mild mitigation that does not magically protect you from the effects of XSS.


How to Change a Culture of "Security Through Obscurity" I have worked for a number of organizations in the past that utilize practices that are justified by what I would describe as "Security through Obscurity" including the following:

Weak/Vulnerable two way hashing of passwords
Utilizing various API's/Utilities know to all to contain serious vulnerabilities
Various forms of data/code obfuscation
Sloppy/No user management
The continued use of incredibly insecure passwords
(The list goes on and on...)

Often times the fixes to these issues do not involve a large investment/change and I find it easy to get resources aligned to resolve them. My issue is in justifying any potential fixes, when these practices are challenged typically the concerns are dismissed with comments such as:

"only group xyz has access to that network/product/machine/login/whatever"
"that isn't a big concern" - The unstated version of:
"no one could guess that/know to test that"

Even when in environments where security is very taken seriously, and audits are an ongoing concern, I have always found it challenging to convince others(especially non-technical/managerial types) of the importance of designing and maintaining systems that are secure by design.

I've found that when you use an example people will agree with you on principal, but the lesson really never sinks in. When confronted with an thorough explanation of why a particular system/subsystem is vulnerable management will often fall back on "it's not a priority right now"(I can't defend it and I don't care) argument, valid in it's own right, but more times than not rather than identifying and logging the issue, reflecting on lessons learned, and establishing a schedule to meet a certain pre-definded level of compliance, management often times discards any evidence contrary to full compliance, ensures all related parties that the previously mentioned system is "secure", and ships the product.

I am of the opinion that security through obscurity is not an effective part of a secure system and that resources spent of such schema's are resources better used for other parts of the application.

I've found over my career that the most difficult part of implementing a secure system is not convincing others of the value of a secure system or in gathering the requisite resources, but in convincing others of this principal. Efforts expended to improve an organizations security often turn into one man crusades rather than systematic and long term changes in culture and practice.

At the risk of being to broad or generally opinion based, what are the best strategies for teaching others the value and reasoning behind avoiding "Security through Obscurity"?

In this situation, you are likely going to need management to set standards and force change. But you have to communicate to management in a particular way.

Step 1: do a risk assessment. Although a certain issue might not be best practice, is the cost of the change going to save the company any money or reduce risk to a point under the risk threshold? This is something that can help get management (potentially) on board.

Step 2: show how other teams or companies have avoided problems, gained customer confidence, or seen success by doing things differently. Showing where other companies had problems will not work.

Step 3: start with small changes by getting an ally (person or team) to go through the change process as a "pilot" with strong and visible management support. Support them in whatever way they need to be successful. Document the challenges and successes and broadcast them to the rest of the teams.

Step 4: measure and document the benefits of the change, both in terms of the benefits to the development teams and to management and the company as a whole (if possible).

Step 5: ask for a volunteer team to try out the new approach on another small-ish but bigger pilot. Repeat steps 3 - 5.

The 2 big things you need to be able to track is the benefit to management to keep doing this (in terms that they understand), and the benefits to the development teams to want to do this (in terms that they understand).

It's easy to get a culture to change if everyone is benefitting. It can be very difficult to show those benefits in real terms, but well worth the effort. I've seen massive change in teams and companies in a short time using this type of approach.


How harmful is it to expose access token to the resource owner? While checking the facebook php sdk implementation I noticed that they expose the access token to the resource owner (user)

$params = array(
  'next' => $next,
  'access_token' => $session->getToken()
);
return 'https://www.facebook.com/logout.php?' . http_build_query($params, null, '&');

FacebookRedirectLoginHelper.php#L155

How harmful is it considered to be? I cannot explain it, but it just does not look right.

In case it's not "the best practice" how would one implement a logout using oauth v2 flow instead?

I have made some research in the specification and that's what I've found:

  Don't pass bearer tokens in page URLs:  Bearer tokens SHOULD NOT be
        passed in page URLs (for example, as query string parameters).

http://tools.ietf.org/html/rfc6750#section-5.3

It is true that bearer tokens and session tokens should not be passed int he url. The reasons are (according to OWASP):

  might disclose the session ID (in web links and logs, web browser history and bookmarks, the Referer header or search engines)

In this specific case, I think Facebook did not care since the usage is logout - so after it has been called the token is not usable anymore any way, so no big deal if it is leaked.


Encrypting With Passwords - Encryption of Key vs. Data Many password-based encryption utilities (e.g.: KeePass, TrueCrypt) do something along the lines of...

Encrypt data with super-strong random-generated key, "data key".
Encrypt data key with another key, "user key", based on user-provided password.
When access is needed, user provides password. Password is used to recreate user key, which decrypts data key, which decrypts the data.

Presumably the logic behind that is this:

User-provided passwords suck, so we need a better key to protect the data.
Users still need access to the data, so we need a way for them to do it with a password.

However, the bottom line of all this is that the protection of the data still boils down to the strength and protection of the user-provided password. So, what's the real point of the extra overhead in having a separate key involved?

The main advantage of using an intermediate key is that is allows changing your password without reprocessing all the data.

E.g. you have a big file (gigabytes...) encrypted with random key K (a 128-bit value), and K is itself encrypted with P (the key derived from the password). If you change your password, you get a new password-derived key P'. To adjust things, you must then decrypt K with P and reencrypt it with P'. This does not require reencrypting or even accessing the big file.

Apart from that advantage, using an intermediate key decouples the operation, which is more flexible. For instance, the process used to turn the password into a symmetric key might not be up to the task of producing a key of the length you want for bulk encryption (for instance, bcrypt will produce a 192-bit key, not a 256-bit key).

Another advantage of the intermediate key is that it allows revealing files. For instance, you have your big file, and you want to show it to Bob. But you do not want to give your password to Bob; you want Bob to be able to see that single file, not all other files which are morally encrypted with the same password. With the intermediate key, this is easy: you just show K to Bob. As long as each file has its own random K, this works.

Note that the model extends to asymmetric encryption: a file sent to n recipients will be encrypted once with a random key K, and K will be encrypted with the public keys of each recipient. This is how things work in OpenPGP. The corresponding advantages map to the password-based situation as well.


How can I protect myself from someone taking over my mobile phone number? I don't know much about security and don't know if these things are possible or not.

Last night I received a text message stating "Please use ****** to authenticate your phone number in the DIGITS from T-Mobile app"

I looked up information about the DIGITS from T-Mobile app and it looks like this is the message you are sent when you try to register a phone number with it. I don't have a T-Mobile SIM card and did not try registering it with this app, so it seems that somebody else has tried to.

I believe it could be an honest mistake, that somebody may have fat-fingered my phone number instead of theirs, but in case it was intentional, is it possible for this person to successfully spoof my number? If they were able to register it with DIGITS, then they will receive any future text messages, which is particularly concerning because I have a number of accounts who use 2-factor authentication via SMS. And is there anything I can do to either prevent my number from being spoofed, or at the very least, to protect myself in the event of my number being spoofed?

Anything at all to help me understand security better and to protect myself is very welcome!

As a 'consumer', you can get a HackRF One, and run OpenBTS on your PC. You can make your own low-power IMSI-catcher, but more interestingly you can view most of the physical layer stuff of mobile networks. You can view the signal strength of towers and peers. You can make your PC beep if some parameters change. OpenBTS is very well-documented. Don't worry too much though, just assume pwnage and act accordingly.

Use OpenVPN/Opera VPN, and additionally use Wire/WhatsApp/Signal/Facetime/iMessage/etc for calls and messaging, don't use normal SMS and voicecalls. You can't stop IMSI-catchers with off-the-shelf phones anyway, and one individual with a HackRF can snoop on your old-world calls and texts, after downgrading you to 2G/GSM. Who you gonna call?