Global variables and information securityCan ads on a page read my password?Vertical information portal security with a customized web browserWhat are some vulnerabilities of environment variables (on any platform)?Azure Key Vault vs Azure Environment Variables - Which is the right way?Can environment variables created for a unix account be viewable by another account?Plain text Rails environment variables and securityWhat security advantages does Hashicorp Vault have over storing secrets (passwords, API keys) in environment variables?Is it unsafe to use environmental variables for secret data?

Can there be plants on the dark side of a tidally locked world?

What drugs were used in England during the High Middle Ages?

Baking with Whey Protein

The little bee buzzes around the flower garden

How to find better food in airports

Why didn't Thatcher give Hong Kong to Taiwan?

Archiving processor does not archive

How do you manage to study and have a balance in your life at the same time?

If p-value is exactly 1 (1.0000000), what are the confidence interval limits?

What did Boris Johnson mean when he said "extra 34 billion going into the NHS"

Punishment in pacifist society

Time to call the bluff

How to generate all 3×3 matrices with a,a,a,a,b,b,b,c,c?

How many days for hunting?

Short story with a first person narrator in a future where racial conflict had exploded into an all out war

Which is the best password hashing algorithm in .NET Core?

How do I stop making people jump at home and at work?

Typesetting a comma unless before a line break

Importance of electrolytic capacitor size

What exactly is a softlock?

Count rook moves 1D

Real-world issues with using an alias

Can a country avoid prosecution for crimes against humanity by denying it happened?

How did Gollum know Sauron was gathering the Haradrim to make war?



Global variables and information security


Can ads on a page read my password?Vertical information portal security with a customized web browserWhat are some vulnerabilities of environment variables (on any platform)?Azure Key Vault vs Azure Environment Variables - Which is the right way?Can environment variables created for a unix account be viewable by another account?Plain text Rails environment variables and securityWhat security advantages does Hashicorp Vault have over storing secrets (passwords, API keys) in environment variables?Is it unsafe to use environmental variables for secret data?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








30















I get the impression that it is a programming best practice to create variables in specific scopes (like a function scope) and avoid global scope to make things more modular and better organized. However I'm not sure if there is also a security issue.



Here is an example of global variables in Bash that worked for me fine more than a year:



cat <<-EOF >> "$HOME"/.profile
set -x
complete -r
export war="/var/www/html" # Web Application Root;
export dmp="phpminiadmin" # Database Management Program;

export -f war
war()
cd $war/

EOF

source "$HOME"/.profile 2>/dev/null


I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?










share|improve this question





















  • 55





    "Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

    – Steffen Ullrich
    yesterday







  • 11





    A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

    – Steve Sether
    19 hours ago






  • 11





    There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

    – whatsisname
    18 hours ago






  • 8





    @SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

    – FooBar
    14 hours ago






  • 7





    You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

    – AccountantM
    13 hours ago


















30















I get the impression that it is a programming best practice to create variables in specific scopes (like a function scope) and avoid global scope to make things more modular and better organized. However I'm not sure if there is also a security issue.



Here is an example of global variables in Bash that worked for me fine more than a year:



cat <<-EOF >> "$HOME"/.profile
set -x
complete -r
export war="/var/www/html" # Web Application Root;
export dmp="phpminiadmin" # Database Management Program;

export -f war
war()
cd $war/

EOF

source "$HOME"/.profile 2>/dev/null


I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?










share|improve this question





















  • 55





    "Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

    – Steffen Ullrich
    yesterday







  • 11





    A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

    – Steve Sether
    19 hours ago






  • 11





    There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

    – whatsisname
    18 hours ago






  • 8





    @SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

    – FooBar
    14 hours ago






  • 7





    You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

    – AccountantM
    13 hours ago














30












30








30


13






I get the impression that it is a programming best practice to create variables in specific scopes (like a function scope) and avoid global scope to make things more modular and better organized. However I'm not sure if there is also a security issue.



Here is an example of global variables in Bash that worked for me fine more than a year:



cat <<-EOF >> "$HOME"/.profile
set -x
complete -r
export war="/var/www/html" # Web Application Root;
export dmp="phpminiadmin" # Database Management Program;

export -f war
war()
cd $war/

EOF

source "$HOME"/.profile 2>/dev/null


I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?










share|improve this question
















I get the impression that it is a programming best practice to create variables in specific scopes (like a function scope) and avoid global scope to make things more modular and better organized. However I'm not sure if there is also a security issue.



Here is an example of global variables in Bash that worked for me fine more than a year:



cat <<-EOF >> "$HOME"/.profile
set -x
complete -r
export war="/var/www/html" # Web Application Root;
export dmp="phpminiadmin" # Database Management Program;

export -f war
war()
cd $war/

EOF

source "$HOME"/.profile 2>/dev/null


I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?







access-control environment-variables breach






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 15 mins ago







JohnDoea

















asked yesterday









JohnDoeaJohnDoea

1872 gold badges8 silver badges22 bronze badges




1872 gold badges8 silver badges22 bronze badges










  • 55





    "Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

    – Steffen Ullrich
    yesterday







  • 11





    A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

    – Steve Sether
    19 hours ago






  • 11





    There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

    – whatsisname
    18 hours ago






  • 8





    @SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

    – FooBar
    14 hours ago






  • 7





    You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

    – AccountantM
    13 hours ago













  • 55





    "Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

    – Steffen Ullrich
    yesterday







  • 11





    A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

    – Steve Sether
    19 hours ago






  • 11





    There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

    – whatsisname
    18 hours ago






  • 8





    @SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

    – FooBar
    14 hours ago






  • 7





    You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

    – AccountantM
    13 hours ago








55




55





"Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

– Steffen Ullrich
yesterday






"Why many programmers abstain from using global variables?" - because it is much easier to understand and verify small code snippets which have no side effects. When using global variables you always have to be aware which part of the code might change it in what way and what the effect will be - which is really hard with a larger code base and more than trivial global variables without obvious behavior (i.e. some global debug variable might be fine). See also Global Variables Are Bad.

– Steffen Ullrich
yesterday





11




11





A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

– Steve Sether
19 hours ago





A more general idea of why developers hate global variables is because they can cause "action at a distance" en.wikipedia.org/wiki/…

– Steve Sether
19 hours ago




11




11





There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

– whatsisname
18 hours ago





There is really nothing wrong with global variables if you're only ever writing "small" scripts. It's when you build medium to large scripts or programs that they become a nightmare.

– whatsisname
18 hours ago




8




8





@SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

– FooBar
14 hours ago





@SteffenUllrich Please post your anwer as an answer, not a comment. Comments are not meant to be permanent, furthermore you're dodging the community's ability to downvote answers.

– FooBar
14 hours ago




7




7





You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

– AccountantM
13 hours ago






You discovered a bug in your code that your global variable is empty, while it shouldn't. Now go and search in all of your 500 files , which peace of code in these 500 files changed the value to 0 ?

– AccountantM
13 hours ago











9 Answers
9






active

oldest

votes


















53
















Boycott Globals!



I'm stealing from Steffen Ullrich's comment, but the main issue with global variables is that they make it difficult to keep code well organized and maintainable. His link is a fine one, but you won't have any trouble finding countless articles about the problems with global variables online.



When you use global variables, it becomes easy to lose track of where in your program the variable gets modified, especially if you don't have a simple linear flow. As a result global variables can work perfectly fine in small scripts, but can cause massive headaches as an application begins to scale.



The main reason why I would avoid globals is because they make automated unit/integration testing a nightmare. Small applications can survive without tests, but trying to manage a larger application without good tests is just a nightmare (trust me, I tried in my young-and-foolish days).



This might leave you with the impression that globals are fine in very small applications, but since applications usually only grow over time, and things that start off temporary become permanent, it's really just a bad idea to use them at all. Why start on the wrong foot, when it is so easy to use properly scoped variables?



Security



Using global variables doesn't have any direct implications for security, but they do make it easier to end up with security issues:



If one loses track of where data comes from and modifies a function in file A but forgets that the utilized variable comes from user input in file B, it might end up doing insecure things on user input without proper safe guards.



Technically this is possible in any application, but global variables can certainly make it easier.



Global Variables == Death



I don't know of any breaches that happened specifically because of global variables, but it's easy to argue that the use of global variables has literally killed people, so I think it's reasonable to just never use them.



Examples



This is a good case where an example can help. For my example I'm going to harken back to the days of good ol' PHP in the early '00s. Many PHP frameworks from those days were filled with global variables and a complete lack of variable scope (aka this example is based on actual code I've seen over the years). Usually there is some settings.php file that creates lots of global variables:



settings.php:



$success_message = 'Your request was successful';


And then some sort of "controller" that does something and includes a php file that acts as the view:



register.php



if ($success) 
include 'success.php';



success.php



<h2><?= $success_message ?></h2>


But then someone decides it would be better to include the user's name in the message when they submit the contact form.



The developer who receives this feature request comes up with a great way to make this happen for the contact form and other places that ask for a name. Therefore they do things "smart", go to the very bottom of settings.php and add this gem at the bottom:



(modified) settings.php



$success_message = 'Your request was successful';

// 100 other lines for various settings

$success_message .= " $GLOBALS['name']";


In case you didn't catch it, they just introduced a nearly system-wide XSS vulnerability. They took user input and dropped it into a global variable that previously contained perfectly safe data. This variable has now changed from innocuous to dangerous, with no warning. Someone looking at success.php will see it output a system-wide variable defined in settings.php. They will look in settings.php and see that it is defined as a constant, and is perfectly safe. They don't have any reason to scroll down and notice the fact that the whole system is completely owned.



That is the root of the issue. Doing something silly like the above and adding user input to a variable is an easy mistake to make. The issue with global variables is that it can completely separate related code, so when someone tries to track the flow of data through the application, they have to hunt through the whole source code to find potential changes. As a result it is very easy to introduce breaking vulnerabilities without realizing it, and it is is even easier for those issues to go unnoticed for extended periods of time.





share






















  • 22





    the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

    – Ray
    19 hours ago







  • 13





    This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

    – Cort Ammon
    18 hours ago






  • 20





    @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

    – Anders
    15 hours ago






  • 2





    @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

    – Conor Mancone
    10 hours ago






  • 3





    @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

    – Graham
    9 hours ago



















8
















In some programming environments, you can't trust the global scope since other sources could read / mess with it.



This has already led to some critical vulnerabilities in security sensitive products, like a remote code execution in the LastPass browser extension.






share|improve this answer
































    7
















    Please compare the following pieces of code:



    1)



    /file.php:
    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;','username','password');


    2)



    ../secrets.php:
    $mysqlusername = 'username';
    $mysqlpassword = 'password';

    /file.php:
    require_once('../secrets.php');
    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername,$mysqlpassword);


    3



    ../secrets.php:
    function pdoconn(i)
    $mysqlusername = ['username1','username2'];
    $mysqlpassword = ['password1','password2'];
    $conn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername[i],$mysqlpassword[i]);
    return $conn;


    /file.php:
    require_once('../secrets.php');
    $newconn = pdoconn(0);


    Example 1 is out of the question - incorrect configuration on production servers could end up showing sensitive parameters to unintended parties.



    Example 2 is better, but those variables are available throughout the application, and modifiable, which could result in errors.



    Example 3 keeps things very organised and transferable.

    It can be modified to use globals if ../secrets.php instead was:



    ../secrets.php:
    $mysqlusername = 'username';
    $mysqlpassword = 'password';
    function pdoconn()
    $conn = new
    PDO('mysql:host=localhost;charset=utf8mb4;',$GLOBALS['mysqlusername'],$GLOBALS['mysqlpassword']);
    return $conn;



    And I think that demonstrates why a global doesn't make sense most of the time in quite a succinct way.




    Summary:



    As for security breaches using global variables (and why I wrote these examples in PHP), there was quite a (at the time) controversial change in PHP 4.2.0 where register_globals was turned on to off. I can't find any articles now, as this change was made in 2002, but I do seem to remember it being responsible for a few breaches at the time. Copying directly from the manual, there is a very clear example of vulnerable code:



    <?php
    // define $authorized = true only if user is authenticated
    if (authenticated_user())
    $authorized = true;


    // Because we didn't first initialize $authorized as false, this might be
    // defined through register_globals, like from GET auth.php?authorized=1
    // So, anyone can be seen as authenticated!
    if ($authorized)
    include "/highly/sensitive/data.php";

    ?>





    share|improve this answer










    New contributor



    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















    • I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

      – Anders
      15 hours ago






    • 1





      @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

      – LTPCGO
      15 hours ago











    • My point is that you should not keep passwords in the source code at all, even if it is in a function.

      – Anders
      14 hours ago











    • I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

      – LTPCGO
      14 hours ago











    • Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

      – JohnDoea
      7 hours ago


















    4
















    They can give code injections easier access to everything



    In PHP there is the $GLOBALS superglobal; in Python there is the globals() function, and in Javascript there is the window (or in Node, process) object. These all make it trivial to enumerate all global variables.



    Once you do that you can both suck out the information they contain and change them maliciously. For example, if sensitive data is stored in a global, an attacker could easily extract it. If, say, a database connection URL is stored in a global, an attacker could point the URL to refer to the attacker's server instead, and then the victim would attempt to connect to that server and send credentials.



    Also, if you have a lot of global objects then you can call their methods with ease.



    They violate "principle of least privilege"



    This principle of security engineering basically says "don't give someone more access than they need in order to do their job". Every function and method can read and write global variables even if they are totally irrelevant to its job, which means that if that piece of code is hijacked even in some limited way, it will open up a greater attack surface.



    (Of course, most scripting languages have weak encapsulation rules which is also a violation of POLP, but if objects are out of scope then it is a lot harder to do anything to them.)



    They are a breeding ground for buggy code



    For reasons including:



    • the programmer forgetting that one of the variables in a function is a global and thus changes made to it will persist when the function ends,

    • the non-obvious sensitivity of the program to the order in which functions are called

    • the ease with which cascade failures can happen (e.g. when a function sets a global to null and later another one crashes)

    • the highly complex interactions which can easily occur and are hard to reason about

    They are simply untidy



    If you think about a business where there are papers strewn everywhere, things aren't organised and filed away neatly but just lying around, who's going to notice if something goes missing? If an employee commits fraud nobody will spot the discrepancy because discrepancies are everywhere. If a pair of keys goes missing, someone will just assume they're buried under something or someone had to borrow them.



    Now you might say this is an exaggeration, but if so I doubt you've ever worked with a big software project. Globals are OK if your website is small enough to build in a couple of days (and you know what you're doing). They can save time to get something going.



    But they don't scale.





    share

























    • Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

      – JohnDoea
      42 mins ago


















    3
















    Because the use of global variables gives you a bunch of problems, and not really any benefits.



    Globals make your code hard to test



    While not directly related to security, unit tests are vital to development. And in order to properly unit-test something, you need to be able to control the exact context in which code is executed. Look at the two pieces of code:



    With Globals



    public Money CalculateExpenses(int departmentId)

    Department department = (from d in global_db.Departments
    where d.Id = departmentId
    select d).Single();

    return (from ex in department.Expenses
    select ex).Sum();



    Without Globals



    public Money CalculateExpenses(int departmentId, Database database)

    Department department = (from d in database.Departments
    where d.Id = departmentId
    select d).Single();

    return (from ex in department.Expenses
    select ex).Sum();



    You might say that the code looks almost identical, except for where the data is actually coming from. You might even think that the code with Globals is "cleaner", because you don't have to pass the database every time.



    Until you have to write a unit test. Because then you will have to insert some logic to not connect to the production database, but rather some local, perhaps test-specific database. Now the non-Global code looks much better, because you can just pass the database you would like to use to the code.



    In Summary: Code without Globals is easier to test.



    Globals change behavior if you don't change the code



    If your code has around 200 lines of code, then the usage of Globals doesn't seem so bad. In fact, it may seem like a perfectly valid thing to do if you re-use the same piece of code all over the place (e.g. some random data source, logging, etc.)



    However, once your codebase grows enough, the introduction of globals can be absolutely deadly. You simply lose control over where your data is from, and who has access to it.



    Let's use an example in everyone's favorite language: PHP 5. Example by Eevee.



     @fopen('http://example.com/not-existing-file', 'r');


    What does this code do? You don't know, because it depends on global behavior. If PHP was compiled with --disable-url-fopen-wrapper, then it will not work. Same for the global configuration allow_url_fopen. We don't know what it will do.



    The @ int the beginning will disable error messages, unless scream.enabled is set in the global PHP config. It will also not be printed if the global error_reporting level is not set. Where exactly it will be printed to, if it prints, will depends on the global display_errors.



    So as you saw, the behavior of one innocuous line depends on 5 different global variables. Now imagine this scenario in a code base with one million lines, and 100 different programmers, all across different teams, and you will quickly see why the use of Globals is abhorrent and leads to all sorts of problems.



    Imagine going to work one day and your code suddenly breaks, even though you haven't touched it. That's the magic of Globals.



    There are more examples of why the use of Globals are bad, which can be found in the other answers.






    share|improve this answer
































      3
















      Buffer Overflow Attacks



      While fairly language-specific ( C/C++ come to mind ), and difficult to pull off, they are a potential attack.



      Computerphile has a great video about it, that I wholeheartedly recommend, but here's a short version of the mechanics of this attacks and how it interacts with global variables.




      A buffer overflow occurs when data written to a buffer also corrupts data values in memory addresses adjacent to the destination buffer due to insufficient bounds checking. This can occur when copying data from one buffer to another without first checking that the data fits within the destination buffer. (Wikipedia)




      In the case of global variables, your program's memory layout is fairly static.



      This is not specific to global variables, but holding meaningful information in such structures facilitates ( not to be mistaken with enabling! ) these kinds of attacks.






      share|improve this answer










      New contributor



      Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
















      • 1





        I don't see what this has to do specifically with global variables. Can you please elaborate?

        – Kami Kaze
        9 hours ago


















      1

















      I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



      Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?




      In tiny projects global variables are just fine. Most of their problems don't show up.



      And your entire customized bash environment state? Tiny.



      Global variables start causing problems as your program scales. This happens in a bunch of ways.



      But the core part of the problem is the amount of state that understanding each piece of code requires.



      Imagine a 10 million line code base. In it, there are 1 million variables. All of them are global.



      In a given 100 line piece of code, you might use 20 variables.



      Whenever you call another function, you have no idea which of those 20 variables that other function will modify. When your function starts, you have no idea where the variable state came from.



      So to understand what your 100 lines of code mean, you need to either understand and hold in your head all 10 million lines of code, or you need some kind of convention about where data is coming from, what data can and cannot be modified when you call a helper function, etc.



      In contrast, if your code is almost entirely fueled by function arguments, local variables and return types, you only have to understand your function to understand what it does.



      If it calls another function, you know what information you are passing to it, and what information it passes back. You might not know what it does with that information, but you know what it doesn't do. It cannot modify integer x and you are certain, because you didn't pass x to the function, nor did you assign to it from its return value!



      Making code easier to reason about locally is a very important goal. You want to be able to read a function, know what it is doing, and identify bugs.



      Writing code is far, far easier and far, far less important than making code that is clear and easy to reason about. Almost all code in a large, persitent project gets read 100s of times more often than it is modified, and it is written and designed once.




      From this rule -- make stuff easier to reason about locally -- we reach the rule of "avoid global state".



      Global variables that are read/written are an example of global state. But so can be some super-object that everything in your project has a pointer to passed as the first argument.



      A super-object still has advantages over global variables; global variables often have confusing mechanics on how they are initialized and cleaned up (I'm looking at you, C/C++), and if you have a super-object with all of your "global" state you can instantiate two versions of your super-object and run both at the same time in the same process (this will tend not to work, but that is usually because of some implicit global state the OS foists on you).



      Every global variable you read, instead of a parameter, means that any bit of code, anywhere could be modifying your behavior. Every global variable you write to means you are changing the behavior of some code arbitrarily far away.



      And it isn't just humans who find global state a pain. If your state is local, writing test harnesses that "fake" a global state or environment becomes far easier. If there is (say) a global "mouse" object, writing a unit test that creates a fake mouse that pretends to do certain movement becomes harder. It may even be harder to write a macro that plays back a recorded mouse movement into some code, especially if you intend to do it while the UI remains responsive to the actual human using a mouse.




      Security is a function of understanding what your code does. Security, within a program, means "your code only does what it is intended to be allowed to do"; with global variables, you have a weaker ability to understand what the code does, thus less ability to control what it does.






      share|improve this answer
































        0
















        Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?


        Because it's easier to modify code that doesn't use global variables to run in unintended applications, applications which the original developer didn't foresee. Really, if you depend on global state, you can have at most one such state in an application without intensive refactoring (which would refactor away the global state).



        Such unintended applications might include making the code run in multi-threaded environments.



        However, what many people fail to realize: malloc() is global!



        The same people who advocate against using global variables are all the time using a global allocator state.



        This means that if piece of your code allocates lots of memory, making malloc() request more memory from the operating system, the memory blocks get mixed up with those allocated from other pieces of your code, and when the same piece of code frees all of its memory it was using, the free() calls don't return memory back to the operating system due to fragmentation. The end result is that your program ends up using more memory than it should.



        So, the very people who advocate against using global variables, are in fact using an allocator with a global state.



        I wonder why none of the standards by the major standardization organizations (C89/C99/C11/C18 by ISO, POSIX by IEEE) have defined an allocator that allows you to have multiple allocator states, i.e. independent heaps.






        share|improve this answer
































          0
















          If just about every programming language can declare a variable globally, accessible only within the scope of it's implementation code, then this is a non-issue. There isn't much reason to use global variables.



          Yet, this isn't the case, which is why when I've found myself writing my projects in C & not in C++, where it is naturally supported as a static variable at the outermost clause of a class definition, I've had to make do with global variables.






          share|improve this answer










          New contributor



          Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "162"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            noCode: true, onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsecurity.stackexchange.com%2fquestions%2f216421%2fglobal-variables-and-information-security%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            9 Answers
            9






            active

            oldest

            votes








            9 Answers
            9






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            53
















            Boycott Globals!



            I'm stealing from Steffen Ullrich's comment, but the main issue with global variables is that they make it difficult to keep code well organized and maintainable. His link is a fine one, but you won't have any trouble finding countless articles about the problems with global variables online.



            When you use global variables, it becomes easy to lose track of where in your program the variable gets modified, especially if you don't have a simple linear flow. As a result global variables can work perfectly fine in small scripts, but can cause massive headaches as an application begins to scale.



            The main reason why I would avoid globals is because they make automated unit/integration testing a nightmare. Small applications can survive without tests, but trying to manage a larger application without good tests is just a nightmare (trust me, I tried in my young-and-foolish days).



            This might leave you with the impression that globals are fine in very small applications, but since applications usually only grow over time, and things that start off temporary become permanent, it's really just a bad idea to use them at all. Why start on the wrong foot, when it is so easy to use properly scoped variables?



            Security



            Using global variables doesn't have any direct implications for security, but they do make it easier to end up with security issues:



            If one loses track of where data comes from and modifies a function in file A but forgets that the utilized variable comes from user input in file B, it might end up doing insecure things on user input without proper safe guards.



            Technically this is possible in any application, but global variables can certainly make it easier.



            Global Variables == Death



            I don't know of any breaches that happened specifically because of global variables, but it's easy to argue that the use of global variables has literally killed people, so I think it's reasonable to just never use them.



            Examples



            This is a good case where an example can help. For my example I'm going to harken back to the days of good ol' PHP in the early '00s. Many PHP frameworks from those days were filled with global variables and a complete lack of variable scope (aka this example is based on actual code I've seen over the years). Usually there is some settings.php file that creates lots of global variables:



            settings.php:



            $success_message = 'Your request was successful';


            And then some sort of "controller" that does something and includes a php file that acts as the view:



            register.php



            if ($success) 
            include 'success.php';



            success.php



            <h2><?= $success_message ?></h2>


            But then someone decides it would be better to include the user's name in the message when they submit the contact form.



            The developer who receives this feature request comes up with a great way to make this happen for the contact form and other places that ask for a name. Therefore they do things "smart", go to the very bottom of settings.php and add this gem at the bottom:



            (modified) settings.php



            $success_message = 'Your request was successful';

            // 100 other lines for various settings

            $success_message .= " $GLOBALS['name']";


            In case you didn't catch it, they just introduced a nearly system-wide XSS vulnerability. They took user input and dropped it into a global variable that previously contained perfectly safe data. This variable has now changed from innocuous to dangerous, with no warning. Someone looking at success.php will see it output a system-wide variable defined in settings.php. They will look in settings.php and see that it is defined as a constant, and is perfectly safe. They don't have any reason to scroll down and notice the fact that the whole system is completely owned.



            That is the root of the issue. Doing something silly like the above and adding user input to a variable is an easy mistake to make. The issue with global variables is that it can completely separate related code, so when someone tries to track the flow of data through the application, they have to hunt through the whole source code to find potential changes. As a result it is very easy to introduce breaking vulnerabilities without realizing it, and it is is even easier for those issues to go unnoticed for extended periods of time.





            share






















            • 22





              the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

              – Ray
              19 hours ago







            • 13





              This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

              – Cort Ammon
              18 hours ago






            • 20





              @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

              – Anders
              15 hours ago






            • 2





              @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

              – Conor Mancone
              10 hours ago






            • 3





              @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

              – Graham
              9 hours ago
















            53
















            Boycott Globals!



            I'm stealing from Steffen Ullrich's comment, but the main issue with global variables is that they make it difficult to keep code well organized and maintainable. His link is a fine one, but you won't have any trouble finding countless articles about the problems with global variables online.



            When you use global variables, it becomes easy to lose track of where in your program the variable gets modified, especially if you don't have a simple linear flow. As a result global variables can work perfectly fine in small scripts, but can cause massive headaches as an application begins to scale.



            The main reason why I would avoid globals is because they make automated unit/integration testing a nightmare. Small applications can survive without tests, but trying to manage a larger application without good tests is just a nightmare (trust me, I tried in my young-and-foolish days).



            This might leave you with the impression that globals are fine in very small applications, but since applications usually only grow over time, and things that start off temporary become permanent, it's really just a bad idea to use them at all. Why start on the wrong foot, when it is so easy to use properly scoped variables?



            Security



            Using global variables doesn't have any direct implications for security, but they do make it easier to end up with security issues:



            If one loses track of where data comes from and modifies a function in file A but forgets that the utilized variable comes from user input in file B, it might end up doing insecure things on user input without proper safe guards.



            Technically this is possible in any application, but global variables can certainly make it easier.



            Global Variables == Death



            I don't know of any breaches that happened specifically because of global variables, but it's easy to argue that the use of global variables has literally killed people, so I think it's reasonable to just never use them.



            Examples



            This is a good case where an example can help. For my example I'm going to harken back to the days of good ol' PHP in the early '00s. Many PHP frameworks from those days were filled with global variables and a complete lack of variable scope (aka this example is based on actual code I've seen over the years). Usually there is some settings.php file that creates lots of global variables:



            settings.php:



            $success_message = 'Your request was successful';


            And then some sort of "controller" that does something and includes a php file that acts as the view:



            register.php



            if ($success) 
            include 'success.php';



            success.php



            <h2><?= $success_message ?></h2>


            But then someone decides it would be better to include the user's name in the message when they submit the contact form.



            The developer who receives this feature request comes up with a great way to make this happen for the contact form and other places that ask for a name. Therefore they do things "smart", go to the very bottom of settings.php and add this gem at the bottom:



            (modified) settings.php



            $success_message = 'Your request was successful';

            // 100 other lines for various settings

            $success_message .= " $GLOBALS['name']";


            In case you didn't catch it, they just introduced a nearly system-wide XSS vulnerability. They took user input and dropped it into a global variable that previously contained perfectly safe data. This variable has now changed from innocuous to dangerous, with no warning. Someone looking at success.php will see it output a system-wide variable defined in settings.php. They will look in settings.php and see that it is defined as a constant, and is perfectly safe. They don't have any reason to scroll down and notice the fact that the whole system is completely owned.



            That is the root of the issue. Doing something silly like the above and adding user input to a variable is an easy mistake to make. The issue with global variables is that it can completely separate related code, so when someone tries to track the flow of data through the application, they have to hunt through the whole source code to find potential changes. As a result it is very easy to introduce breaking vulnerabilities without realizing it, and it is is even easier for those issues to go unnoticed for extended periods of time.





            share






















            • 22





              the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

              – Ray
              19 hours ago







            • 13





              This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

              – Cort Ammon
              18 hours ago






            • 20





              @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

              – Anders
              15 hours ago






            • 2





              @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

              – Conor Mancone
              10 hours ago






            • 3





              @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

              – Graham
              9 hours ago














            53














            53










            53









            Boycott Globals!



            I'm stealing from Steffen Ullrich's comment, but the main issue with global variables is that they make it difficult to keep code well organized and maintainable. His link is a fine one, but you won't have any trouble finding countless articles about the problems with global variables online.



            When you use global variables, it becomes easy to lose track of where in your program the variable gets modified, especially if you don't have a simple linear flow. As a result global variables can work perfectly fine in small scripts, but can cause massive headaches as an application begins to scale.



            The main reason why I would avoid globals is because they make automated unit/integration testing a nightmare. Small applications can survive without tests, but trying to manage a larger application without good tests is just a nightmare (trust me, I tried in my young-and-foolish days).



            This might leave you with the impression that globals are fine in very small applications, but since applications usually only grow over time, and things that start off temporary become permanent, it's really just a bad idea to use them at all. Why start on the wrong foot, when it is so easy to use properly scoped variables?



            Security



            Using global variables doesn't have any direct implications for security, but they do make it easier to end up with security issues:



            If one loses track of where data comes from and modifies a function in file A but forgets that the utilized variable comes from user input in file B, it might end up doing insecure things on user input without proper safe guards.



            Technically this is possible in any application, but global variables can certainly make it easier.



            Global Variables == Death



            I don't know of any breaches that happened specifically because of global variables, but it's easy to argue that the use of global variables has literally killed people, so I think it's reasonable to just never use them.



            Examples



            This is a good case where an example can help. For my example I'm going to harken back to the days of good ol' PHP in the early '00s. Many PHP frameworks from those days were filled with global variables and a complete lack of variable scope (aka this example is based on actual code I've seen over the years). Usually there is some settings.php file that creates lots of global variables:



            settings.php:



            $success_message = 'Your request was successful';


            And then some sort of "controller" that does something and includes a php file that acts as the view:



            register.php



            if ($success) 
            include 'success.php';



            success.php



            <h2><?= $success_message ?></h2>


            But then someone decides it would be better to include the user's name in the message when they submit the contact form.



            The developer who receives this feature request comes up with a great way to make this happen for the contact form and other places that ask for a name. Therefore they do things "smart", go to the very bottom of settings.php and add this gem at the bottom:



            (modified) settings.php



            $success_message = 'Your request was successful';

            // 100 other lines for various settings

            $success_message .= " $GLOBALS['name']";


            In case you didn't catch it, they just introduced a nearly system-wide XSS vulnerability. They took user input and dropped it into a global variable that previously contained perfectly safe data. This variable has now changed from innocuous to dangerous, with no warning. Someone looking at success.php will see it output a system-wide variable defined in settings.php. They will look in settings.php and see that it is defined as a constant, and is perfectly safe. They don't have any reason to scroll down and notice the fact that the whole system is completely owned.



            That is the root of the issue. Doing something silly like the above and adding user input to a variable is an easy mistake to make. The issue with global variables is that it can completely separate related code, so when someone tries to track the flow of data through the application, they have to hunt through the whole source code to find potential changes. As a result it is very easy to introduce breaking vulnerabilities without realizing it, and it is is even easier for those issues to go unnoticed for extended periods of time.





            share















            Boycott Globals!



            I'm stealing from Steffen Ullrich's comment, but the main issue with global variables is that they make it difficult to keep code well organized and maintainable. His link is a fine one, but you won't have any trouble finding countless articles about the problems with global variables online.



            When you use global variables, it becomes easy to lose track of where in your program the variable gets modified, especially if you don't have a simple linear flow. As a result global variables can work perfectly fine in small scripts, but can cause massive headaches as an application begins to scale.



            The main reason why I would avoid globals is because they make automated unit/integration testing a nightmare. Small applications can survive without tests, but trying to manage a larger application without good tests is just a nightmare (trust me, I tried in my young-and-foolish days).



            This might leave you with the impression that globals are fine in very small applications, but since applications usually only grow over time, and things that start off temporary become permanent, it's really just a bad idea to use them at all. Why start on the wrong foot, when it is so easy to use properly scoped variables?



            Security



            Using global variables doesn't have any direct implications for security, but they do make it easier to end up with security issues:



            If one loses track of where data comes from and modifies a function in file A but forgets that the utilized variable comes from user input in file B, it might end up doing insecure things on user input without proper safe guards.



            Technically this is possible in any application, but global variables can certainly make it easier.



            Global Variables == Death



            I don't know of any breaches that happened specifically because of global variables, but it's easy to argue that the use of global variables has literally killed people, so I think it's reasonable to just never use them.



            Examples



            This is a good case where an example can help. For my example I'm going to harken back to the days of good ol' PHP in the early '00s. Many PHP frameworks from those days were filled with global variables and a complete lack of variable scope (aka this example is based on actual code I've seen over the years). Usually there is some settings.php file that creates lots of global variables:



            settings.php:



            $success_message = 'Your request was successful';


            And then some sort of "controller" that does something and includes a php file that acts as the view:



            register.php



            if ($success) 
            include 'success.php';



            success.php



            <h2><?= $success_message ?></h2>


            But then someone decides it would be better to include the user's name in the message when they submit the contact form.



            The developer who receives this feature request comes up with a great way to make this happen for the contact form and other places that ask for a name. Therefore they do things "smart", go to the very bottom of settings.php and add this gem at the bottom:



            (modified) settings.php



            $success_message = 'Your request was successful';

            // 100 other lines for various settings

            $success_message .= " $GLOBALS['name']";


            In case you didn't catch it, they just introduced a nearly system-wide XSS vulnerability. They took user input and dropped it into a global variable that previously contained perfectly safe data. This variable has now changed from innocuous to dangerous, with no warning. Someone looking at success.php will see it output a system-wide variable defined in settings.php. They will look in settings.php and see that it is defined as a constant, and is perfectly safe. They don't have any reason to scroll down and notice the fact that the whole system is completely owned.



            That is the root of the issue. Doing something silly like the above and adding user input to a variable is an easy mistake to make. The issue with global variables is that it can completely separate related code, so when someone tries to track the flow of data through the application, they have to hunt through the whole source code to find potential changes. As a result it is very easy to introduce breaking vulnerabilities without realizing it, and it is is even easier for those issues to go unnoticed for extended periods of time.






            share













            share


            share








            edited 9 hours ago









            yoozer8

            1781 gold badge2 silver badges11 bronze badges




            1781 gold badge2 silver badges11 bronze badges










            answered yesterday









            Conor ManconeConor Mancone

            14.6k6 gold badges44 silver badges62 bronze badges




            14.6k6 gold badges44 silver badges62 bronze badges










            • 22





              the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

              – Ray
              19 hours ago







            • 13





              This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

              – Cort Ammon
              18 hours ago






            • 20





              @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

              – Anders
              15 hours ago






            • 2





              @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

              – Conor Mancone
              10 hours ago






            • 3





              @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

              – Graham
              9 hours ago













            • 22





              the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

              – Ray
              19 hours ago







            • 13





              This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

              – Cort Ammon
              18 hours ago






            • 20





              @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

              – Anders
              15 hours ago






            • 2





              @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

              – Conor Mancone
              10 hours ago






            • 3





              @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

              – Graham
              9 hours ago








            22




            22





            the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

            – Ray
            19 hours ago






            the use of global variables has literally killed people, so I think it's reasonable to just never use them. By that logic, we should never use cars.

            – Ray
            19 hours ago





            13




            13





            This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

            – Cort Ammon
            18 hours ago





            This also explains why globals are okay for small programs. Programmers want the use of their variables scoped, and a small program is a small enough scope to work with!

            – Cort Ammon
            18 hours ago




            20




            20





            @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

            – Anders
            15 hours ago





            @Ray Proper scoping is the seat belts of programming. We shouldn't drive without it.

            – Anders
            15 hours ago




            2




            2





            @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

            – Conor Mancone
            10 hours ago





            @Ray Considering how easy it is to not use global variables, and the very many downsides of their use, I think it's easy case to make a case for not using them. Granted, that part of my answer was obviously a little over the top ("GLOBAL VARIABLES KILL PEOPLE!!!!!"), but it's not that often that programming leads to death, so I'm going to stick with my slightly-over-dramatic statement :p

            – Conor Mancone
            10 hours ago




            3




            3





            @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

            – Graham
            9 hours ago






            @ConorMancone Re your last link, I'm in the interesting position of having written the safety integrity checker for Ford's Escape hybrid. Virtually all real-time embedded code uses global variables throughout, for efficiency, so it's too harsh to criticise Toyota for that. Where they absolutely do deserve criticism is slapdash development practises, where misuse of global variables is just one symptom of an overall lack of professionalism. For ourselves, we took it seriously, and we got our development processes and our code externally audited to prove that.

            – Graham
            9 hours ago














            8
















            In some programming environments, you can't trust the global scope since other sources could read / mess with it.



            This has already led to some critical vulnerabilities in security sensitive products, like a remote code execution in the LastPass browser extension.






            share|improve this answer





























              8
















              In some programming environments, you can't trust the global scope since other sources could read / mess with it.



              This has already led to some critical vulnerabilities in security sensitive products, like a remote code execution in the LastPass browser extension.






              share|improve this answer



























                8














                8










                8









                In some programming environments, you can't trust the global scope since other sources could read / mess with it.



                This has already led to some critical vulnerabilities in security sensitive products, like a remote code execution in the LastPass browser extension.






                share|improve this answer













                In some programming environments, you can't trust the global scope since other sources could read / mess with it.



                This has already led to some critical vulnerabilities in security sensitive products, like a remote code execution in the LastPass browser extension.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 14 hours ago









                Benoit EsnardBenoit Esnard

                11.4k7 gold badges56 silver badges58 bronze badges




                11.4k7 gold badges56 silver badges58 bronze badges
























                    7
















                    Please compare the following pieces of code:



                    1)



                    /file.php:
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;','username','password');


                    2)



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';

                    /file.php:
                    require_once('../secrets.php');
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername,$mysqlpassword);


                    3



                    ../secrets.php:
                    function pdoconn(i)
                    $mysqlusername = ['username1','username2'];
                    $mysqlpassword = ['password1','password2'];
                    $conn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername[i],$mysqlpassword[i]);
                    return $conn;


                    /file.php:
                    require_once('../secrets.php');
                    $newconn = pdoconn(0);


                    Example 1 is out of the question - incorrect configuration on production servers could end up showing sensitive parameters to unintended parties.



                    Example 2 is better, but those variables are available throughout the application, and modifiable, which could result in errors.



                    Example 3 keeps things very organised and transferable.

                    It can be modified to use globals if ../secrets.php instead was:



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';
                    function pdoconn()
                    $conn = new
                    PDO('mysql:host=localhost;charset=utf8mb4;',$GLOBALS['mysqlusername'],$GLOBALS['mysqlpassword']);
                    return $conn;



                    And I think that demonstrates why a global doesn't make sense most of the time in quite a succinct way.




                    Summary:



                    As for security breaches using global variables (and why I wrote these examples in PHP), there was quite a (at the time) controversial change in PHP 4.2.0 where register_globals was turned on to off. I can't find any articles now, as this change was made in 2002, but I do seem to remember it being responsible for a few breaches at the time. Copying directly from the manual, there is a very clear example of vulnerable code:



                    <?php
                    // define $authorized = true only if user is authenticated
                    if (authenticated_user())
                    $authorized = true;


                    // Because we didn't first initialize $authorized as false, this might be
                    // defined through register_globals, like from GET auth.php?authorized=1
                    // So, anyone can be seen as authenticated!
                    if ($authorized)
                    include "/highly/sensitive/data.php";

                    ?>





                    share|improve this answer










                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





















                    • I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                      – Anders
                      15 hours ago






                    • 1





                      @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                      – LTPCGO
                      15 hours ago











                    • My point is that you should not keep passwords in the source code at all, even if it is in a function.

                      – Anders
                      14 hours ago











                    • I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                      – LTPCGO
                      14 hours ago











                    • Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                      – JohnDoea
                      7 hours ago















                    7
















                    Please compare the following pieces of code:



                    1)



                    /file.php:
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;','username','password');


                    2)



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';

                    /file.php:
                    require_once('../secrets.php');
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername,$mysqlpassword);


                    3



                    ../secrets.php:
                    function pdoconn(i)
                    $mysqlusername = ['username1','username2'];
                    $mysqlpassword = ['password1','password2'];
                    $conn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername[i],$mysqlpassword[i]);
                    return $conn;


                    /file.php:
                    require_once('../secrets.php');
                    $newconn = pdoconn(0);


                    Example 1 is out of the question - incorrect configuration on production servers could end up showing sensitive parameters to unintended parties.



                    Example 2 is better, but those variables are available throughout the application, and modifiable, which could result in errors.



                    Example 3 keeps things very organised and transferable.

                    It can be modified to use globals if ../secrets.php instead was:



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';
                    function pdoconn()
                    $conn = new
                    PDO('mysql:host=localhost;charset=utf8mb4;',$GLOBALS['mysqlusername'],$GLOBALS['mysqlpassword']);
                    return $conn;



                    And I think that demonstrates why a global doesn't make sense most of the time in quite a succinct way.




                    Summary:



                    As for security breaches using global variables (and why I wrote these examples in PHP), there was quite a (at the time) controversial change in PHP 4.2.0 where register_globals was turned on to off. I can't find any articles now, as this change was made in 2002, but I do seem to remember it being responsible for a few breaches at the time. Copying directly from the manual, there is a very clear example of vulnerable code:



                    <?php
                    // define $authorized = true only if user is authenticated
                    if (authenticated_user())
                    $authorized = true;


                    // Because we didn't first initialize $authorized as false, this might be
                    // defined through register_globals, like from GET auth.php?authorized=1
                    // So, anyone can be seen as authenticated!
                    if ($authorized)
                    include "/highly/sensitive/data.php";

                    ?>





                    share|improve this answer










                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





















                    • I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                      – Anders
                      15 hours ago






                    • 1





                      @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                      – LTPCGO
                      15 hours ago











                    • My point is that you should not keep passwords in the source code at all, even if it is in a function.

                      – Anders
                      14 hours ago











                    • I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                      – LTPCGO
                      14 hours ago











                    • Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                      – JohnDoea
                      7 hours ago













                    7














                    7










                    7









                    Please compare the following pieces of code:



                    1)



                    /file.php:
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;','username','password');


                    2)



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';

                    /file.php:
                    require_once('../secrets.php');
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername,$mysqlpassword);


                    3



                    ../secrets.php:
                    function pdoconn(i)
                    $mysqlusername = ['username1','username2'];
                    $mysqlpassword = ['password1','password2'];
                    $conn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername[i],$mysqlpassword[i]);
                    return $conn;


                    /file.php:
                    require_once('../secrets.php');
                    $newconn = pdoconn(0);


                    Example 1 is out of the question - incorrect configuration on production servers could end up showing sensitive parameters to unintended parties.



                    Example 2 is better, but those variables are available throughout the application, and modifiable, which could result in errors.



                    Example 3 keeps things very organised and transferable.

                    It can be modified to use globals if ../secrets.php instead was:



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';
                    function pdoconn()
                    $conn = new
                    PDO('mysql:host=localhost;charset=utf8mb4;',$GLOBALS['mysqlusername'],$GLOBALS['mysqlpassword']);
                    return $conn;



                    And I think that demonstrates why a global doesn't make sense most of the time in quite a succinct way.




                    Summary:



                    As for security breaches using global variables (and why I wrote these examples in PHP), there was quite a (at the time) controversial change in PHP 4.2.0 where register_globals was turned on to off. I can't find any articles now, as this change was made in 2002, but I do seem to remember it being responsible for a few breaches at the time. Copying directly from the manual, there is a very clear example of vulnerable code:



                    <?php
                    // define $authorized = true only if user is authenticated
                    if (authenticated_user())
                    $authorized = true;


                    // Because we didn't first initialize $authorized as false, this might be
                    // defined through register_globals, like from GET auth.php?authorized=1
                    // So, anyone can be seen as authenticated!
                    if ($authorized)
                    include "/highly/sensitive/data.php";

                    ?>





                    share|improve this answer










                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    Please compare the following pieces of code:



                    1)



                    /file.php:
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;','username','password');


                    2)



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';

                    /file.php:
                    require_once('../secrets.php');
                    $newconn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername,$mysqlpassword);


                    3



                    ../secrets.php:
                    function pdoconn(i)
                    $mysqlusername = ['username1','username2'];
                    $mysqlpassword = ['password1','password2'];
                    $conn = new PDO('mysql:host=localhost;charset=utf8mb4;',$mysqlusername[i],$mysqlpassword[i]);
                    return $conn;


                    /file.php:
                    require_once('../secrets.php');
                    $newconn = pdoconn(0);


                    Example 1 is out of the question - incorrect configuration on production servers could end up showing sensitive parameters to unintended parties.



                    Example 2 is better, but those variables are available throughout the application, and modifiable, which could result in errors.



                    Example 3 keeps things very organised and transferable.

                    It can be modified to use globals if ../secrets.php instead was:



                    ../secrets.php:
                    $mysqlusername = 'username';
                    $mysqlpassword = 'password';
                    function pdoconn()
                    $conn = new
                    PDO('mysql:host=localhost;charset=utf8mb4;',$GLOBALS['mysqlusername'],$GLOBALS['mysqlpassword']);
                    return $conn;



                    And I think that demonstrates why a global doesn't make sense most of the time in quite a succinct way.




                    Summary:



                    As for security breaches using global variables (and why I wrote these examples in PHP), there was quite a (at the time) controversial change in PHP 4.2.0 where register_globals was turned on to off. I can't find any articles now, as this change was made in 2002, but I do seem to remember it being responsible for a few breaches at the time. Copying directly from the manual, there is a very clear example of vulnerable code:



                    <?php
                    // define $authorized = true only if user is authenticated
                    if (authenticated_user())
                    $authorized = true;


                    // Because we didn't first initialize $authorized as false, this might be
                    // defined through register_globals, like from GET auth.php?authorized=1
                    // So, anyone can be seen as authenticated!
                    if ($authorized)
                    include "/highly/sensitive/data.php";

                    ?>






                    share|improve this answer










                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.








                    share|improve this answer



                    share|improve this answer








                    edited 21 hours ago









                    JohnDoea

                    1872 gold badges8 silver badges22 bronze badges




                    1872 gold badges8 silver badges22 bronze badges






                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.








                    answered 22 hours ago









                    LTPCGOLTPCGO

                    1369 bronze badges




                    1369 bronze badges




                    New contributor



                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.




                    New contributor




                    LTPCGO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.

















                    • I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                      – Anders
                      15 hours ago






                    • 1





                      @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                      – LTPCGO
                      15 hours ago











                    • My point is that you should not keep passwords in the source code at all, even if it is in a function.

                      – Anders
                      14 hours ago











                    • I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                      – LTPCGO
                      14 hours ago











                    • Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                      – JohnDoea
                      7 hours ago

















                    • I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                      – Anders
                      15 hours ago






                    • 1





                      @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                      – LTPCGO
                      15 hours ago











                    • My point is that you should not keep passwords in the source code at all, even if it is in a function.

                      – Anders
                      14 hours ago











                    • I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                      – LTPCGO
                      14 hours ago











                    • Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                      – JohnDoea
                      7 hours ago
















                    I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                    – Anders
                    15 hours ago





                    I'd say #3 is also bad, because the password is in the source code! You still have all the same issues with accidental exposure. Great example at the end though!

                    – Anders
                    15 hours ago




                    1




                    1





                    @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                    – LTPCGO
                    15 hours ago





                    @Anders maybe it's not clear, where I have to keep the file on the same server, I use a function similar to this in place of just having a variable with the password stored in a file, since when that is included it is normally available globally. Essentially you keep it the same as what I think you're suggesting, but instead of referring to a variable when it's required you instead call a function to return the object required.

                    – LTPCGO
                    15 hours ago













                    My point is that you should not keep passwords in the source code at all, even if it is in a function.

                    – Anders
                    14 hours ago





                    My point is that you should not keep passwords in the source code at all, even if it is in a function.

                    – Anders
                    14 hours ago













                    I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                    – LTPCGO
                    14 hours ago





                    I'm saying it's not in the source code though, it would sit in a file somewhere on the server that you include_once(). Unless you're talking about not keeping the password on the server at all and instead accessing credentials via an API, which I 100% agree with and aim to do in every situation that it can possibly be done.

                    – LTPCGO
                    14 hours ago













                    Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                    – JohnDoea
                    7 hours ago





                    Example 1 examples how incorrect configuration on production servers could end up showing values of sensitive parameters to unintended parties. Do you mean to case that both values would appear in Query Strings?

                    – JohnDoea
                    7 hours ago











                    4
















                    They can give code injections easier access to everything



                    In PHP there is the $GLOBALS superglobal; in Python there is the globals() function, and in Javascript there is the window (or in Node, process) object. These all make it trivial to enumerate all global variables.



                    Once you do that you can both suck out the information they contain and change them maliciously. For example, if sensitive data is stored in a global, an attacker could easily extract it. If, say, a database connection URL is stored in a global, an attacker could point the URL to refer to the attacker's server instead, and then the victim would attempt to connect to that server and send credentials.



                    Also, if you have a lot of global objects then you can call their methods with ease.



                    They violate "principle of least privilege"



                    This principle of security engineering basically says "don't give someone more access than they need in order to do their job". Every function and method can read and write global variables even if they are totally irrelevant to its job, which means that if that piece of code is hijacked even in some limited way, it will open up a greater attack surface.



                    (Of course, most scripting languages have weak encapsulation rules which is also a violation of POLP, but if objects are out of scope then it is a lot harder to do anything to them.)



                    They are a breeding ground for buggy code



                    For reasons including:



                    • the programmer forgetting that one of the variables in a function is a global and thus changes made to it will persist when the function ends,

                    • the non-obvious sensitivity of the program to the order in which functions are called

                    • the ease with which cascade failures can happen (e.g. when a function sets a global to null and later another one crashes)

                    • the highly complex interactions which can easily occur and are hard to reason about

                    They are simply untidy



                    If you think about a business where there are papers strewn everywhere, things aren't organised and filed away neatly but just lying around, who's going to notice if something goes missing? If an employee commits fraud nobody will spot the discrepancy because discrepancies are everywhere. If a pair of keys goes missing, someone will just assume they're buried under something or someone had to borrow them.



                    Now you might say this is an exaggeration, but if so I doubt you've ever worked with a big software project. Globals are OK if your website is small enough to build in a couple of days (and you know what you're doing). They can save time to get something going.



                    But they don't scale.





                    share

























                    • Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                      – JohnDoea
                      42 mins ago















                    4
















                    They can give code injections easier access to everything



                    In PHP there is the $GLOBALS superglobal; in Python there is the globals() function, and in Javascript there is the window (or in Node, process) object. These all make it trivial to enumerate all global variables.



                    Once you do that you can both suck out the information they contain and change them maliciously. For example, if sensitive data is stored in a global, an attacker could easily extract it. If, say, a database connection URL is stored in a global, an attacker could point the URL to refer to the attacker's server instead, and then the victim would attempt to connect to that server and send credentials.



                    Also, if you have a lot of global objects then you can call their methods with ease.



                    They violate "principle of least privilege"



                    This principle of security engineering basically says "don't give someone more access than they need in order to do their job". Every function and method can read and write global variables even if they are totally irrelevant to its job, which means that if that piece of code is hijacked even in some limited way, it will open up a greater attack surface.



                    (Of course, most scripting languages have weak encapsulation rules which is also a violation of POLP, but if objects are out of scope then it is a lot harder to do anything to them.)



                    They are a breeding ground for buggy code



                    For reasons including:



                    • the programmer forgetting that one of the variables in a function is a global and thus changes made to it will persist when the function ends,

                    • the non-obvious sensitivity of the program to the order in which functions are called

                    • the ease with which cascade failures can happen (e.g. when a function sets a global to null and later another one crashes)

                    • the highly complex interactions which can easily occur and are hard to reason about

                    They are simply untidy



                    If you think about a business where there are papers strewn everywhere, things aren't organised and filed away neatly but just lying around, who's going to notice if something goes missing? If an employee commits fraud nobody will spot the discrepancy because discrepancies are everywhere. If a pair of keys goes missing, someone will just assume they're buried under something or someone had to borrow them.



                    Now you might say this is an exaggeration, but if so I doubt you've ever worked with a big software project. Globals are OK if your website is small enough to build in a couple of days (and you know what you're doing). They can save time to get something going.



                    But they don't scale.





                    share

























                    • Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                      – JohnDoea
                      42 mins ago













                    4














                    4










                    4









                    They can give code injections easier access to everything



                    In PHP there is the $GLOBALS superglobal; in Python there is the globals() function, and in Javascript there is the window (or in Node, process) object. These all make it trivial to enumerate all global variables.



                    Once you do that you can both suck out the information they contain and change them maliciously. For example, if sensitive data is stored in a global, an attacker could easily extract it. If, say, a database connection URL is stored in a global, an attacker could point the URL to refer to the attacker's server instead, and then the victim would attempt to connect to that server and send credentials.



                    Also, if you have a lot of global objects then you can call their methods with ease.



                    They violate "principle of least privilege"



                    This principle of security engineering basically says "don't give someone more access than they need in order to do their job". Every function and method can read and write global variables even if they are totally irrelevant to its job, which means that if that piece of code is hijacked even in some limited way, it will open up a greater attack surface.



                    (Of course, most scripting languages have weak encapsulation rules which is also a violation of POLP, but if objects are out of scope then it is a lot harder to do anything to them.)



                    They are a breeding ground for buggy code



                    For reasons including:



                    • the programmer forgetting that one of the variables in a function is a global and thus changes made to it will persist when the function ends,

                    • the non-obvious sensitivity of the program to the order in which functions are called

                    • the ease with which cascade failures can happen (e.g. when a function sets a global to null and later another one crashes)

                    • the highly complex interactions which can easily occur and are hard to reason about

                    They are simply untidy



                    If you think about a business where there are papers strewn everywhere, things aren't organised and filed away neatly but just lying around, who's going to notice if something goes missing? If an employee commits fraud nobody will spot the discrepancy because discrepancies are everywhere. If a pair of keys goes missing, someone will just assume they're buried under something or someone had to borrow them.



                    Now you might say this is an exaggeration, but if so I doubt you've ever worked with a big software project. Globals are OK if your website is small enough to build in a couple of days (and you know what you're doing). They can save time to get something going.



                    But they don't scale.





                    share













                    They can give code injections easier access to everything



                    In PHP there is the $GLOBALS superglobal; in Python there is the globals() function, and in Javascript there is the window (or in Node, process) object. These all make it trivial to enumerate all global variables.



                    Once you do that you can both suck out the information they contain and change them maliciously. For example, if sensitive data is stored in a global, an attacker could easily extract it. If, say, a database connection URL is stored in a global, an attacker could point the URL to refer to the attacker's server instead, and then the victim would attempt to connect to that server and send credentials.



                    Also, if you have a lot of global objects then you can call their methods with ease.



                    They violate "principle of least privilege"



                    This principle of security engineering basically says "don't give someone more access than they need in order to do their job". Every function and method can read and write global variables even if they are totally irrelevant to its job, which means that if that piece of code is hijacked even in some limited way, it will open up a greater attack surface.



                    (Of course, most scripting languages have weak encapsulation rules which is also a violation of POLP, but if objects are out of scope then it is a lot harder to do anything to them.)



                    They are a breeding ground for buggy code



                    For reasons including:



                    • the programmer forgetting that one of the variables in a function is a global and thus changes made to it will persist when the function ends,

                    • the non-obvious sensitivity of the program to the order in which functions are called

                    • the ease with which cascade failures can happen (e.g. when a function sets a global to null and later another one crashes)

                    • the highly complex interactions which can easily occur and are hard to reason about

                    They are simply untidy



                    If you think about a business where there are papers strewn everywhere, things aren't organised and filed away neatly but just lying around, who's going to notice if something goes missing? If an employee commits fraud nobody will spot the discrepancy because discrepancies are everywhere. If a pair of keys goes missing, someone will just assume they're buried under something or someone had to borrow them.



                    Now you might say this is an exaggeration, but if so I doubt you've ever worked with a big software project. Globals are OK if your website is small enough to build in a couple of days (and you know what you're doing). They can save time to get something going.



                    But they don't scale.






                    share











                    share


                    share










                    answered 11 hours ago









                    ArteliusArtelius

                    4682 silver badges4 bronze badges




                    4682 silver badges4 bronze badges















                    • Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                      – JohnDoea
                      42 mins ago

















                    • Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                      – JohnDoea
                      42 mins ago
















                    Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                    – JohnDoea
                    42 mins ago





                    Hello, I like this answer in general; I didn't say what you wrote is an exaggeration; the "big software project" part seems to me redundant and better to be deleted because there is no explanation to what you mean in general or specifically. Thanks,

                    – JohnDoea
                    42 mins ago











                    3
















                    Because the use of global variables gives you a bunch of problems, and not really any benefits.



                    Globals make your code hard to test



                    While not directly related to security, unit tests are vital to development. And in order to properly unit-test something, you need to be able to control the exact context in which code is executed. Look at the two pieces of code:



                    With Globals



                    public Money CalculateExpenses(int departmentId)

                    Department department = (from d in global_db.Departments
                    where d.Id = departmentId
                    select d).Single();

                    return (from ex in department.Expenses
                    select ex).Sum();



                    Without Globals



                    public Money CalculateExpenses(int departmentId, Database database)

                    Department department = (from d in database.Departments
                    where d.Id = departmentId
                    select d).Single();

                    return (from ex in department.Expenses
                    select ex).Sum();



                    You might say that the code looks almost identical, except for where the data is actually coming from. You might even think that the code with Globals is "cleaner", because you don't have to pass the database every time.



                    Until you have to write a unit test. Because then you will have to insert some logic to not connect to the production database, but rather some local, perhaps test-specific database. Now the non-Global code looks much better, because you can just pass the database you would like to use to the code.



                    In Summary: Code without Globals is easier to test.



                    Globals change behavior if you don't change the code



                    If your code has around 200 lines of code, then the usage of Globals doesn't seem so bad. In fact, it may seem like a perfectly valid thing to do if you re-use the same piece of code all over the place (e.g. some random data source, logging, etc.)



                    However, once your codebase grows enough, the introduction of globals can be absolutely deadly. You simply lose control over where your data is from, and who has access to it.



                    Let's use an example in everyone's favorite language: PHP 5. Example by Eevee.



                     @fopen('http://example.com/not-existing-file', 'r');


                    What does this code do? You don't know, because it depends on global behavior. If PHP was compiled with --disable-url-fopen-wrapper, then it will not work. Same for the global configuration allow_url_fopen. We don't know what it will do.



                    The @ int the beginning will disable error messages, unless scream.enabled is set in the global PHP config. It will also not be printed if the global error_reporting level is not set. Where exactly it will be printed to, if it prints, will depends on the global display_errors.



                    So as you saw, the behavior of one innocuous line depends on 5 different global variables. Now imagine this scenario in a code base with one million lines, and 100 different programmers, all across different teams, and you will quickly see why the use of Globals is abhorrent and leads to all sorts of problems.



                    Imagine going to work one day and your code suddenly breaks, even though you haven't touched it. That's the magic of Globals.



                    There are more examples of why the use of Globals are bad, which can be found in the other answers.






                    share|improve this answer





























                      3
















                      Because the use of global variables gives you a bunch of problems, and not really any benefits.



                      Globals make your code hard to test



                      While not directly related to security, unit tests are vital to development. And in order to properly unit-test something, you need to be able to control the exact context in which code is executed. Look at the two pieces of code:



                      With Globals



                      public Money CalculateExpenses(int departmentId)

                      Department department = (from d in global_db.Departments
                      where d.Id = departmentId
                      select d).Single();

                      return (from ex in department.Expenses
                      select ex).Sum();



                      Without Globals



                      public Money CalculateExpenses(int departmentId, Database database)

                      Department department = (from d in database.Departments
                      where d.Id = departmentId
                      select d).Single();

                      return (from ex in department.Expenses
                      select ex).Sum();



                      You might say that the code looks almost identical, except for where the data is actually coming from. You might even think that the code with Globals is "cleaner", because you don't have to pass the database every time.



                      Until you have to write a unit test. Because then you will have to insert some logic to not connect to the production database, but rather some local, perhaps test-specific database. Now the non-Global code looks much better, because you can just pass the database you would like to use to the code.



                      In Summary: Code without Globals is easier to test.



                      Globals change behavior if you don't change the code



                      If your code has around 200 lines of code, then the usage of Globals doesn't seem so bad. In fact, it may seem like a perfectly valid thing to do if you re-use the same piece of code all over the place (e.g. some random data source, logging, etc.)



                      However, once your codebase grows enough, the introduction of globals can be absolutely deadly. You simply lose control over where your data is from, and who has access to it.



                      Let's use an example in everyone's favorite language: PHP 5. Example by Eevee.



                       @fopen('http://example.com/not-existing-file', 'r');


                      What does this code do? You don't know, because it depends on global behavior. If PHP was compiled with --disable-url-fopen-wrapper, then it will not work. Same for the global configuration allow_url_fopen. We don't know what it will do.



                      The @ int the beginning will disable error messages, unless scream.enabled is set in the global PHP config. It will also not be printed if the global error_reporting level is not set. Where exactly it will be printed to, if it prints, will depends on the global display_errors.



                      So as you saw, the behavior of one innocuous line depends on 5 different global variables. Now imagine this scenario in a code base with one million lines, and 100 different programmers, all across different teams, and you will quickly see why the use of Globals is abhorrent and leads to all sorts of problems.



                      Imagine going to work one day and your code suddenly breaks, even though you haven't touched it. That's the magic of Globals.



                      There are more examples of why the use of Globals are bad, which can be found in the other answers.






                      share|improve this answer



























                        3














                        3










                        3









                        Because the use of global variables gives you a bunch of problems, and not really any benefits.



                        Globals make your code hard to test



                        While not directly related to security, unit tests are vital to development. And in order to properly unit-test something, you need to be able to control the exact context in which code is executed. Look at the two pieces of code:



                        With Globals



                        public Money CalculateExpenses(int departmentId)

                        Department department = (from d in global_db.Departments
                        where d.Id = departmentId
                        select d).Single();

                        return (from ex in department.Expenses
                        select ex).Sum();



                        Without Globals



                        public Money CalculateExpenses(int departmentId, Database database)

                        Department department = (from d in database.Departments
                        where d.Id = departmentId
                        select d).Single();

                        return (from ex in department.Expenses
                        select ex).Sum();



                        You might say that the code looks almost identical, except for where the data is actually coming from. You might even think that the code with Globals is "cleaner", because you don't have to pass the database every time.



                        Until you have to write a unit test. Because then you will have to insert some logic to not connect to the production database, but rather some local, perhaps test-specific database. Now the non-Global code looks much better, because you can just pass the database you would like to use to the code.



                        In Summary: Code without Globals is easier to test.



                        Globals change behavior if you don't change the code



                        If your code has around 200 lines of code, then the usage of Globals doesn't seem so bad. In fact, it may seem like a perfectly valid thing to do if you re-use the same piece of code all over the place (e.g. some random data source, logging, etc.)



                        However, once your codebase grows enough, the introduction of globals can be absolutely deadly. You simply lose control over where your data is from, and who has access to it.



                        Let's use an example in everyone's favorite language: PHP 5. Example by Eevee.



                         @fopen('http://example.com/not-existing-file', 'r');


                        What does this code do? You don't know, because it depends on global behavior. If PHP was compiled with --disable-url-fopen-wrapper, then it will not work. Same for the global configuration allow_url_fopen. We don't know what it will do.



                        The @ int the beginning will disable error messages, unless scream.enabled is set in the global PHP config. It will also not be printed if the global error_reporting level is not set. Where exactly it will be printed to, if it prints, will depends on the global display_errors.



                        So as you saw, the behavior of one innocuous line depends on 5 different global variables. Now imagine this scenario in a code base with one million lines, and 100 different programmers, all across different teams, and you will quickly see why the use of Globals is abhorrent and leads to all sorts of problems.



                        Imagine going to work one day and your code suddenly breaks, even though you haven't touched it. That's the magic of Globals.



                        There are more examples of why the use of Globals are bad, which can be found in the other answers.






                        share|improve this answer













                        Because the use of global variables gives you a bunch of problems, and not really any benefits.



                        Globals make your code hard to test



                        While not directly related to security, unit tests are vital to development. And in order to properly unit-test something, you need to be able to control the exact context in which code is executed. Look at the two pieces of code:



                        With Globals



                        public Money CalculateExpenses(int departmentId)

                        Department department = (from d in global_db.Departments
                        where d.Id = departmentId
                        select d).Single();

                        return (from ex in department.Expenses
                        select ex).Sum();



                        Without Globals



                        public Money CalculateExpenses(int departmentId, Database database)

                        Department department = (from d in database.Departments
                        where d.Id = departmentId
                        select d).Single();

                        return (from ex in department.Expenses
                        select ex).Sum();



                        You might say that the code looks almost identical, except for where the data is actually coming from. You might even think that the code with Globals is "cleaner", because you don't have to pass the database every time.



                        Until you have to write a unit test. Because then you will have to insert some logic to not connect to the production database, but rather some local, perhaps test-specific database. Now the non-Global code looks much better, because you can just pass the database you would like to use to the code.



                        In Summary: Code without Globals is easier to test.



                        Globals change behavior if you don't change the code



                        If your code has around 200 lines of code, then the usage of Globals doesn't seem so bad. In fact, it may seem like a perfectly valid thing to do if you re-use the same piece of code all over the place (e.g. some random data source, logging, etc.)



                        However, once your codebase grows enough, the introduction of globals can be absolutely deadly. You simply lose control over where your data is from, and who has access to it.



                        Let's use an example in everyone's favorite language: PHP 5. Example by Eevee.



                         @fopen('http://example.com/not-existing-file', 'r');


                        What does this code do? You don't know, because it depends on global behavior. If PHP was compiled with --disable-url-fopen-wrapper, then it will not work. Same for the global configuration allow_url_fopen. We don't know what it will do.



                        The @ int the beginning will disable error messages, unless scream.enabled is set in the global PHP config. It will also not be printed if the global error_reporting level is not set. Where exactly it will be printed to, if it prints, will depends on the global display_errors.



                        So as you saw, the behavior of one innocuous line depends on 5 different global variables. Now imagine this scenario in a code base with one million lines, and 100 different programmers, all across different teams, and you will quickly see why the use of Globals is abhorrent and leads to all sorts of problems.



                        Imagine going to work one day and your code suddenly breaks, even though you haven't touched it. That's the magic of Globals.



                        There are more examples of why the use of Globals are bad, which can be found in the other answers.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered 14 hours ago









                        MechMK1MechMK1

                        8,0373 gold badges28 silver badges48 bronze badges




                        8,0373 gold badges28 silver badges48 bronze badges
























                            3
















                            Buffer Overflow Attacks



                            While fairly language-specific ( C/C++ come to mind ), and difficult to pull off, they are a potential attack.



                            Computerphile has a great video about it, that I wholeheartedly recommend, but here's a short version of the mechanics of this attacks and how it interacts with global variables.




                            A buffer overflow occurs when data written to a buffer also corrupts data values in memory addresses adjacent to the destination buffer due to insufficient bounds checking. This can occur when copying data from one buffer to another without first checking that the data fits within the destination buffer. (Wikipedia)




                            In the case of global variables, your program's memory layout is fairly static.



                            This is not specific to global variables, but holding meaningful information in such structures facilitates ( not to be mistaken with enabling! ) these kinds of attacks.






                            share|improve this answer










                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.
















                            • 1





                              I don't see what this has to do specifically with global variables. Can you please elaborate?

                              – Kami Kaze
                              9 hours ago















                            3
















                            Buffer Overflow Attacks



                            While fairly language-specific ( C/C++ come to mind ), and difficult to pull off, they are a potential attack.



                            Computerphile has a great video about it, that I wholeheartedly recommend, but here's a short version of the mechanics of this attacks and how it interacts with global variables.




                            A buffer overflow occurs when data written to a buffer also corrupts data values in memory addresses adjacent to the destination buffer due to insufficient bounds checking. This can occur when copying data from one buffer to another without first checking that the data fits within the destination buffer. (Wikipedia)




                            In the case of global variables, your program's memory layout is fairly static.



                            This is not specific to global variables, but holding meaningful information in such structures facilitates ( not to be mistaken with enabling! ) these kinds of attacks.






                            share|improve this answer










                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.
















                            • 1





                              I don't see what this has to do specifically with global variables. Can you please elaborate?

                              – Kami Kaze
                              9 hours ago













                            3














                            3










                            3









                            Buffer Overflow Attacks



                            While fairly language-specific ( C/C++ come to mind ), and difficult to pull off, they are a potential attack.



                            Computerphile has a great video about it, that I wholeheartedly recommend, but here's a short version of the mechanics of this attacks and how it interacts with global variables.




                            A buffer overflow occurs when data written to a buffer also corrupts data values in memory addresses adjacent to the destination buffer due to insufficient bounds checking. This can occur when copying data from one buffer to another without first checking that the data fits within the destination buffer. (Wikipedia)




                            In the case of global variables, your program's memory layout is fairly static.



                            This is not specific to global variables, but holding meaningful information in such structures facilitates ( not to be mistaken with enabling! ) these kinds of attacks.






                            share|improve this answer










                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.









                            Buffer Overflow Attacks



                            While fairly language-specific ( C/C++ come to mind ), and difficult to pull off, they are a potential attack.



                            Computerphile has a great video about it, that I wholeheartedly recommend, but here's a short version of the mechanics of this attacks and how it interacts with global variables.




                            A buffer overflow occurs when data written to a buffer also corrupts data values in memory addresses adjacent to the destination buffer due to insufficient bounds checking. This can occur when copying data from one buffer to another without first checking that the data fits within the destination buffer. (Wikipedia)




                            In the case of global variables, your program's memory layout is fairly static.



                            This is not specific to global variables, but holding meaningful information in such structures facilitates ( not to be mistaken with enabling! ) these kinds of attacks.







                            share|improve this answer










                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.








                            share|improve this answer



                            share|improve this answer








                            edited 8 hours ago









                            Wai Ha Lee

                            1051 silver badge5 bronze badges




                            1051 silver badge5 bronze badges






                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.








                            answered 15 hours ago









                            Mister AmenMister Amen

                            312 bronze badges




                            312 bronze badges




                            New contributor



                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.




                            New contributor




                            Mister Amen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.












                            • 1





                              I don't see what this has to do specifically with global variables. Can you please elaborate?

                              – Kami Kaze
                              9 hours ago












                            • 1





                              I don't see what this has to do specifically with global variables. Can you please elaborate?

                              – Kami Kaze
                              9 hours ago







                            1




                            1





                            I don't see what this has to do specifically with global variables. Can you please elaborate?

                            – Kami Kaze
                            9 hours ago





                            I don't see what this has to do specifically with global variables. Can you please elaborate?

                            – Kami Kaze
                            9 hours ago











                            1

















                            I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



                            Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?




                            In tiny projects global variables are just fine. Most of their problems don't show up.



                            And your entire customized bash environment state? Tiny.



                            Global variables start causing problems as your program scales. This happens in a bunch of ways.



                            But the core part of the problem is the amount of state that understanding each piece of code requires.



                            Imagine a 10 million line code base. In it, there are 1 million variables. All of them are global.



                            In a given 100 line piece of code, you might use 20 variables.



                            Whenever you call another function, you have no idea which of those 20 variables that other function will modify. When your function starts, you have no idea where the variable state came from.



                            So to understand what your 100 lines of code mean, you need to either understand and hold in your head all 10 million lines of code, or you need some kind of convention about where data is coming from, what data can and cannot be modified when you call a helper function, etc.



                            In contrast, if your code is almost entirely fueled by function arguments, local variables and return types, you only have to understand your function to understand what it does.



                            If it calls another function, you know what information you are passing to it, and what information it passes back. You might not know what it does with that information, but you know what it doesn't do. It cannot modify integer x and you are certain, because you didn't pass x to the function, nor did you assign to it from its return value!



                            Making code easier to reason about locally is a very important goal. You want to be able to read a function, know what it is doing, and identify bugs.



                            Writing code is far, far easier and far, far less important than making code that is clear and easy to reason about. Almost all code in a large, persitent project gets read 100s of times more often than it is modified, and it is written and designed once.




                            From this rule -- make stuff easier to reason about locally -- we reach the rule of "avoid global state".



                            Global variables that are read/written are an example of global state. But so can be some super-object that everything in your project has a pointer to passed as the first argument.



                            A super-object still has advantages over global variables; global variables often have confusing mechanics on how they are initialized and cleaned up (I'm looking at you, C/C++), and if you have a super-object with all of your "global" state you can instantiate two versions of your super-object and run both at the same time in the same process (this will tend not to work, but that is usually because of some implicit global state the OS foists on you).



                            Every global variable you read, instead of a parameter, means that any bit of code, anywhere could be modifying your behavior. Every global variable you write to means you are changing the behavior of some code arbitrarily far away.



                            And it isn't just humans who find global state a pain. If your state is local, writing test harnesses that "fake" a global state or environment becomes far easier. If there is (say) a global "mouse" object, writing a unit test that creates a fake mouse that pretends to do certain movement becomes harder. It may even be harder to write a macro that plays back a recorded mouse movement into some code, especially if you intend to do it while the UI remains responsive to the actual human using a mouse.




                            Security is a function of understanding what your code does. Security, within a program, means "your code only does what it is intended to be allowed to do"; with global variables, you have a weaker ability to understand what the code does, thus less ability to control what it does.






                            share|improve this answer





























                              1

















                              I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



                              Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?




                              In tiny projects global variables are just fine. Most of their problems don't show up.



                              And your entire customized bash environment state? Tiny.



                              Global variables start causing problems as your program scales. This happens in a bunch of ways.



                              But the core part of the problem is the amount of state that understanding each piece of code requires.



                              Imagine a 10 million line code base. In it, there are 1 million variables. All of them are global.



                              In a given 100 line piece of code, you might use 20 variables.



                              Whenever you call another function, you have no idea which of those 20 variables that other function will modify. When your function starts, you have no idea where the variable state came from.



                              So to understand what your 100 lines of code mean, you need to either understand and hold in your head all 10 million lines of code, or you need some kind of convention about where data is coming from, what data can and cannot be modified when you call a helper function, etc.



                              In contrast, if your code is almost entirely fueled by function arguments, local variables and return types, you only have to understand your function to understand what it does.



                              If it calls another function, you know what information you are passing to it, and what information it passes back. You might not know what it does with that information, but you know what it doesn't do. It cannot modify integer x and you are certain, because you didn't pass x to the function, nor did you assign to it from its return value!



                              Making code easier to reason about locally is a very important goal. You want to be able to read a function, know what it is doing, and identify bugs.



                              Writing code is far, far easier and far, far less important than making code that is clear and easy to reason about. Almost all code in a large, persitent project gets read 100s of times more often than it is modified, and it is written and designed once.




                              From this rule -- make stuff easier to reason about locally -- we reach the rule of "avoid global state".



                              Global variables that are read/written are an example of global state. But so can be some super-object that everything in your project has a pointer to passed as the first argument.



                              A super-object still has advantages over global variables; global variables often have confusing mechanics on how they are initialized and cleaned up (I'm looking at you, C/C++), and if you have a super-object with all of your "global" state you can instantiate two versions of your super-object and run both at the same time in the same process (this will tend not to work, but that is usually because of some implicit global state the OS foists on you).



                              Every global variable you read, instead of a parameter, means that any bit of code, anywhere could be modifying your behavior. Every global variable you write to means you are changing the behavior of some code arbitrarily far away.



                              And it isn't just humans who find global state a pain. If your state is local, writing test harnesses that "fake" a global state or environment becomes far easier. If there is (say) a global "mouse" object, writing a unit test that creates a fake mouse that pretends to do certain movement becomes harder. It may even be harder to write a macro that plays back a recorded mouse movement into some code, especially if you intend to do it while the UI remains responsive to the actual human using a mouse.




                              Security is a function of understanding what your code does. Security, within a program, means "your code only does what it is intended to be allowed to do"; with global variables, you have a weaker ability to understand what the code does, thus less ability to control what it does.






                              share|improve this answer



























                                1














                                1










                                1










                                I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



                                Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?




                                In tiny projects global variables are just fine. Most of their problems don't show up.



                                And your entire customized bash environment state? Tiny.



                                Global variables start causing problems as your program scales. This happens in a bunch of ways.



                                But the core part of the problem is the amount of state that understanding each piece of code requires.



                                Imagine a 10 million line code base. In it, there are 1 million variables. All of them are global.



                                In a given 100 line piece of code, you might use 20 variables.



                                Whenever you call another function, you have no idea which of those 20 variables that other function will modify. When your function starts, you have no idea where the variable state came from.



                                So to understand what your 100 lines of code mean, you need to either understand and hold in your head all 10 million lines of code, or you need some kind of convention about where data is coming from, what data can and cannot be modified when you call a helper function, etc.



                                In contrast, if your code is almost entirely fueled by function arguments, local variables and return types, you only have to understand your function to understand what it does.



                                If it calls another function, you know what information you are passing to it, and what information it passes back. You might not know what it does with that information, but you know what it doesn't do. It cannot modify integer x and you are certain, because you didn't pass x to the function, nor did you assign to it from its return value!



                                Making code easier to reason about locally is a very important goal. You want to be able to read a function, know what it is doing, and identify bugs.



                                Writing code is far, far easier and far, far less important than making code that is clear and easy to reason about. Almost all code in a large, persitent project gets read 100s of times more often than it is modified, and it is written and designed once.




                                From this rule -- make stuff easier to reason about locally -- we reach the rule of "avoid global state".



                                Global variables that are read/written are an example of global state. But so can be some super-object that everything in your project has a pointer to passed as the first argument.



                                A super-object still has advantages over global variables; global variables often have confusing mechanics on how they are initialized and cleaned up (I'm looking at you, C/C++), and if you have a super-object with all of your "global" state you can instantiate two versions of your super-object and run both at the same time in the same process (this will tend not to work, but that is usually because of some implicit global state the OS foists on you).



                                Every global variable you read, instead of a parameter, means that any bit of code, anywhere could be modifying your behavior. Every global variable you write to means you are changing the behavior of some code arbitrarily far away.



                                And it isn't just humans who find global state a pain. If your state is local, writing test harnesses that "fake" a global state or environment becomes far easier. If there is (say) a global "mouse" object, writing a unit test that creates a fake mouse that pretends to do certain movement becomes harder. It may even be harder to write a macro that plays back a recorded mouse movement into some code, especially if you intend to do it while the UI remains responsive to the actual human using a mouse.




                                Security is a function of understanding what your code does. Security, within a program, means "your code only does what it is intended to be allowed to do"; with global variables, you have a weaker ability to understand what the code does, thus less ability to control what it does.






                                share|improve this answer














                                I have never had a problem with global variables in Bash or JavaScript, most likely because I only wrote small scripts for personal usage on minimalist environments.



                                Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?




                                In tiny projects global variables are just fine. Most of their problems don't show up.



                                And your entire customized bash environment state? Tiny.



                                Global variables start causing problems as your program scales. This happens in a bunch of ways.



                                But the core part of the problem is the amount of state that understanding each piece of code requires.



                                Imagine a 10 million line code base. In it, there are 1 million variables. All of them are global.



                                In a given 100 line piece of code, you might use 20 variables.



                                Whenever you call another function, you have no idea which of those 20 variables that other function will modify. When your function starts, you have no idea where the variable state came from.



                                So to understand what your 100 lines of code mean, you need to either understand and hold in your head all 10 million lines of code, or you need some kind of convention about where data is coming from, what data can and cannot be modified when you call a helper function, etc.



                                In contrast, if your code is almost entirely fueled by function arguments, local variables and return types, you only have to understand your function to understand what it does.



                                If it calls another function, you know what information you are passing to it, and what information it passes back. You might not know what it does with that information, but you know what it doesn't do. It cannot modify integer x and you are certain, because you didn't pass x to the function, nor did you assign to it from its return value!



                                Making code easier to reason about locally is a very important goal. You want to be able to read a function, know what it is doing, and identify bugs.



                                Writing code is far, far easier and far, far less important than making code that is clear and easy to reason about. Almost all code in a large, persitent project gets read 100s of times more often than it is modified, and it is written and designed once.




                                From this rule -- make stuff easier to reason about locally -- we reach the rule of "avoid global state".



                                Global variables that are read/written are an example of global state. But so can be some super-object that everything in your project has a pointer to passed as the first argument.



                                A super-object still has advantages over global variables; global variables often have confusing mechanics on how they are initialized and cleaned up (I'm looking at you, C/C++), and if you have a super-object with all of your "global" state you can instantiate two versions of your super-object and run both at the same time in the same process (this will tend not to work, but that is usually because of some implicit global state the OS foists on you).



                                Every global variable you read, instead of a parameter, means that any bit of code, anywhere could be modifying your behavior. Every global variable you write to means you are changing the behavior of some code arbitrarily far away.



                                And it isn't just humans who find global state a pain. If your state is local, writing test harnesses that "fake" a global state or environment becomes far easier. If there is (say) a global "mouse" object, writing a unit test that creates a fake mouse that pretends to do certain movement becomes harder. It may even be harder to write a macro that plays back a recorded mouse movement into some code, especially if you intend to do it while the UI remains responsive to the actual human using a mouse.




                                Security is a function of understanding what your code does. Security, within a program, means "your code only does what it is intended to be allowed to do"; with global variables, you have a weaker ability to understand what the code does, thus less ability to control what it does.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered 5 hours ago









                                YakkYakk

                                4492 silver badges7 bronze badges




                                4492 silver badges7 bronze badges
























                                    0
















                                    Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?


                                    Because it's easier to modify code that doesn't use global variables to run in unintended applications, applications which the original developer didn't foresee. Really, if you depend on global state, you can have at most one such state in an application without intensive refactoring (which would refactor away the global state).



                                    Such unintended applications might include making the code run in multi-threaded environments.



                                    However, what many people fail to realize: malloc() is global!



                                    The same people who advocate against using global variables are all the time using a global allocator state.



                                    This means that if piece of your code allocates lots of memory, making malloc() request more memory from the operating system, the memory blocks get mixed up with those allocated from other pieces of your code, and when the same piece of code frees all of its memory it was using, the free() calls don't return memory back to the operating system due to fragmentation. The end result is that your program ends up using more memory than it should.



                                    So, the very people who advocate against using global variables, are in fact using an allocator with a global state.



                                    I wonder why none of the standards by the major standardization organizations (C89/C99/C11/C18 by ISO, POSIX by IEEE) have defined an allocator that allows you to have multiple allocator states, i.e. independent heaps.






                                    share|improve this answer





























                                      0
















                                      Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?


                                      Because it's easier to modify code that doesn't use global variables to run in unintended applications, applications which the original developer didn't foresee. Really, if you depend on global state, you can have at most one such state in an application without intensive refactoring (which would refactor away the global state).



                                      Such unintended applications might include making the code run in multi-threaded environments.



                                      However, what many people fail to realize: malloc() is global!



                                      The same people who advocate against using global variables are all the time using a global allocator state.



                                      This means that if piece of your code allocates lots of memory, making malloc() request more memory from the operating system, the memory blocks get mixed up with those allocated from other pieces of your code, and when the same piece of code frees all of its memory it was using, the free() calls don't return memory back to the operating system due to fragmentation. The end result is that your program ends up using more memory than it should.



                                      So, the very people who advocate against using global variables, are in fact using an allocator with a global state.



                                      I wonder why none of the standards by the major standardization organizations (C89/C99/C11/C18 by ISO, POSIX by IEEE) have defined an allocator that allows you to have multiple allocator states, i.e. independent heaps.






                                      share|improve this answer



























                                        0














                                        0










                                        0









                                        Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?


                                        Because it's easier to modify code that doesn't use global variables to run in unintended applications, applications which the original developer didn't foresee. Really, if you depend on global state, you can have at most one such state in an application without intensive refactoring (which would refactor away the global state).



                                        Such unintended applications might include making the code run in multi-threaded environments.



                                        However, what many people fail to realize: malloc() is global!



                                        The same people who advocate against using global variables are all the time using a global allocator state.



                                        This means that if piece of your code allocates lots of memory, making malloc() request more memory from the operating system, the memory blocks get mixed up with those allocated from other pieces of your code, and when the same piece of code frees all of its memory it was using, the free() calls don't return memory back to the operating system due to fragmentation. The end result is that your program ends up using more memory than it should.



                                        So, the very people who advocate against using global variables, are in fact using an allocator with a global state.



                                        I wonder why none of the standards by the major standardization organizations (C89/C99/C11/C18 by ISO, POSIX by IEEE) have defined an allocator that allows you to have multiple allocator states, i.e. independent heaps.






                                        share|improve this answer













                                        Why do many programmers avoid using global variables and are there any examples of security breaches caused by using global variables?


                                        Because it's easier to modify code that doesn't use global variables to run in unintended applications, applications which the original developer didn't foresee. Really, if you depend on global state, you can have at most one such state in an application without intensive refactoring (which would refactor away the global state).



                                        Such unintended applications might include making the code run in multi-threaded environments.



                                        However, what many people fail to realize: malloc() is global!



                                        The same people who advocate against using global variables are all the time using a global allocator state.



                                        This means that if piece of your code allocates lots of memory, making malloc() request more memory from the operating system, the memory blocks get mixed up with those allocated from other pieces of your code, and when the same piece of code frees all of its memory it was using, the free() calls don't return memory back to the operating system due to fragmentation. The end result is that your program ends up using more memory than it should.



                                        So, the very people who advocate against using global variables, are in fact using an allocator with a global state.



                                        I wonder why none of the standards by the major standardization organizations (C89/C99/C11/C18 by ISO, POSIX by IEEE) have defined an allocator that allows you to have multiple allocator states, i.e. independent heaps.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered 5 hours ago









                                        juhistjuhist

                                        2031 silver badge5 bronze badges




                                        2031 silver badge5 bronze badges
























                                            0
















                                            If just about every programming language can declare a variable globally, accessible only within the scope of it's implementation code, then this is a non-issue. There isn't much reason to use global variables.



                                            Yet, this isn't the case, which is why when I've found myself writing my projects in C & not in C++, where it is naturally supported as a static variable at the outermost clause of a class definition, I've had to make do with global variables.






                                            share|improve this answer










                                            New contributor



                                            Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                            Check out our Code of Conduct.

























                                              0
















                                              If just about every programming language can declare a variable globally, accessible only within the scope of it's implementation code, then this is a non-issue. There isn't much reason to use global variables.



                                              Yet, this isn't the case, which is why when I've found myself writing my projects in C & not in C++, where it is naturally supported as a static variable at the outermost clause of a class definition, I've had to make do with global variables.






                                              share|improve this answer










                                              New contributor



                                              Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                              Check out our Code of Conduct.























                                                0














                                                0










                                                0









                                                If just about every programming language can declare a variable globally, accessible only within the scope of it's implementation code, then this is a non-issue. There isn't much reason to use global variables.



                                                Yet, this isn't the case, which is why when I've found myself writing my projects in C & not in C++, where it is naturally supported as a static variable at the outermost clause of a class definition, I've had to make do with global variables.






                                                share|improve this answer










                                                New contributor



                                                Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.









                                                If just about every programming language can declare a variable globally, accessible only within the scope of it's implementation code, then this is a non-issue. There isn't much reason to use global variables.



                                                Yet, this isn't the case, which is why when I've found myself writing my projects in C & not in C++, where it is naturally supported as a static variable at the outermost clause of a class definition, I've had to make do with global variables.







                                                share|improve this answer










                                                New contributor



                                                Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.








                                                share|improve this answer



                                                share|improve this answer








                                                edited 1 hour ago





















                                                New contributor



                                                Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.








                                                answered 1 hour ago









                                                DehbopDehbop

                                                1011 bronze badge




                                                1011 bronze badge




                                                New contributor



                                                Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.




                                                New contributor




                                                Dehbop is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.
































                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Information Security Stack Exchange!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsecurity.stackexchange.com%2fquestions%2f216421%2fglobal-variables-and-information-security%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480